<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/10/20
 * Time: 10:39
 */
namespace App\Api\Controllers\Glow;

use Alipayopen\Sdk\AopClient;
use Alipayopen\Sdk\Request\AlipayTradeFastpayRefundQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeQueryRequest;
use Alipayopen\Sdk\Request\AlipayTradeRefundRequest;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use App\Api\Controllers\Config\EasyPayConfigController;
use App\Api\Controllers\Config\HConfigController;
use App\Api\Controllers\Config\HkrtConfigController;
use App\Api\Controllers\Config\HuiPayConfigController;
use App\Api\Controllers\Config\HwcPayConfigController;
use App\Api\Controllers\Config\JdConfigController;
use App\Api\Controllers\Config\LianfuConfigController;
use App\Api\Controllers\Config\LianfuyoupayConfigController;
use App\Api\Controllers\Config\LinkageConfigController;
use App\Api\Controllers\Config\LtfConfigController;
use App\Api\Controllers\Config\MyBankConfigController;
use App\Api\Controllers\Config\NewLandConfigController;
use App\Api\Controllers\Config\TfConfigController;
use App\Api\Controllers\Config\VbillConfigController;
use App\Api\Controllers\Config\WeixinConfigController;
use App\Api\Controllers\Config\WftPayConfigController;
use App\Api\Controllers\DuoLaBao\ManageController;
use App\Common\RefundSuccessAction;
use App\Exceptions\BizException;
use App\Models\StorePayWay;
use App\Api\Controllers\MyBank\TradePayController;
use App\Api\Controllers\Newland\PayController;
use App\Api\Controllers\Linkage\PayController as LinkagePayController;
use App\Api\Controllers\WftPay\PayController as WftPayPayController;
use App\Api\Controllers\HwcPay\PayController as HwcPayPayController;
use App\Common\PaySuccessAction;
use App\Models\AlipayAppOauthUsers;
use App\Models\AlipayIsvConfig;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Shop;
use App\Models\Store;
use App\Models\WincodeStore;
use EasyWeChat\Factory;
use function EasyWeChat\Kernel\Support\get_client_ip;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use App\Models\SmsConfig;
use Aliyun\AliSms;

use App\Models\MerchantStore;

/**
 * 处理应答时先判断协议字段返回，
 * <return_code>SUCCESS</status>
 * <return_msg>SYSERR</return_msg>
 * 再判断业务返回，
 * <result_code>FAIL</result_code>
 * 最后判断交易状态
 * <err_code><![CDATA[AUTHCODE_EXPIRE]]></err_code>
 * <err_code_des><![CDATA[二维码已过期，请刷新再试]]></err_code_des>
 *
 * Class IndexController
 * @package App\Api\Controllers\WinCode
 */
class IndexController extends BaseController{
//class IndexController{
    /**
     * 收钱啦与服务端交互
     *
     * 1. 收钱啦需要服务端提供APPID和SECRET用来实现身份标识及加密（可参考签名算中的APPID和SECRET的格式及长度）
     * 2. 附加参数“device_id”为款台的唯一标识，用作收钱啦的唯一身份ID
     * device_id通过客户端激活流程获取，说明如下
     * 1.服务端提供款台密钥(激活码)给商户
     * 2.商户将款台密钥(激活码)输入到客户端
     * 3.客户端post请求服务端激活地址(服务端自定义激活地址) 并获取返回device_id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function interaction(Request $request){
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = $this->xml_to_array($data);
//            Log::info('收钱啦-收钱啦与服务端交互-入参');
//            Log::info($data);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $method = $data['method'] ?? 'device.register'; //device.register
            $version = $data['version'] ?? '1.0.0'; //1.0.0
            $sign = $data['sign'] ?? ''; //签名
            $nonce_str = $data['nonce_str'] ?? ''; //随机数
            $appid = $data['appid'] ?? ''; //
            $device_token = $data['device_token'] ?? ''; //服务端提供的款台密钥(激活码)
            if (!$device_token) {
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '客户端没有收到激活码'
                ]);
            }
            $winCodeStoreObj = WincodeStore::where('activation_code', $device_token)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '激活码尚未绑定门店'
                ]);
            }
            $re_data = [
                'version' => $version,
                'charset' => $this->postCharset,
                'sign_type' => 'MD5',
                'nonce_str' => $this->nonceStr(),
                'return_code' => 'SUCCESS',
                'device_id' => $winCodeStoreObj->device_id,
                'device_name' => '默认',
                'store_name' => $winCodeStoreObj->store_name,
                'logo' => url('/zhifu/img/touxiang.png'),
                'result_code' => 'SUCCESS'
            ];
            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            Log::info('收钱啦与服务端交互-error');
            Log::info($exception->getMessage() .' | '.$exception->getFile().' | '. $exception->getLine());
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    /**
     * 收钱啦 交易操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function scan_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
//            Log::info('收钱啦-交易操作-入参');
//            Log::info($data);
            $data = $this->xml_to_array($data);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            if (!isset($data['method']) || empty($data['method'])) {
                return $this->return_data([
                    'return_code' => 'FALL',
                    'return_msg' => '收钱啦-交易方式未知'
                ]);
            }

            $method = $data['method'];
            switch ($method) {
                case 'trade.micropay': //付款码支付
                    return $this->b_2_c($data);
                    break;
                case 'trade.query': //查询订单
                    return $this->order_query($data);
                    break;
                case 'trade.refund': //退款
                    return $this->refund($data);
                    break;
                case 'trade.refund.query': //退款查询
                    return $this->refund_query($data);
                    break;
            }
        } catch (\Exception $ex) {
            Log::info('收钱啦-扫一扫收款error');
            Log::info($ex->getMessage() .' | '.$ex->getFile().' | '. $ex->getLine());
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage() .' | '. $ex->getLine()
            ];
            return $this->return_data($err);
        }
    }

    /**
     * 付款码支付
     *
     * 1. 支付请求后： return_code 和 result_code 字段返回都为SUCCESS时，判定订单支付成功；
     * 2. 支付请求后： return_code 返回为 SUCCESS，而 result_code 返回不为 SUCCESS 时，并且返回的参数 need_query为 N时，才不用调查询接口，其他情况（包括没有返回 need_query参数， 返回了 need_query 参数但值为Y）则必须调用订单查询接口进行确认
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function b_2_c($data)
    {
        try {
//            Log::info('收钱啦-付款码支付-入参');
//            Log::info($data);

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = $data['device_id'] ?? ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //商户系统内部的订单号,32个字符内、可包含字母,确保在同一商户号下唯一
            $total_fee = $data['total_fee'] ?? 0; //总金额，以分为单位，不允许包含任何字、符号
            $body = $data['body'] ?? ''; //商品描述
            $auth_code = $data['auth_code'] ?? ''; //扫码支付授权码， 设备读取用户展示的条码或者二维码信息
            $op_user = $data['op_user'] ?? ''; //否,String(32),操作员账号
            $attach = $data['attach'] ?? ''; //否,String(128),商户附加信息，可做扩展参数
            $spbill_create_ip = $data['spbill_create_ip'] ?? get_client_ip(); //订单生成的机器 IP (使用收钱啦SDK会默认获取，可选填)
            $time_start = $data['time_start'] ?? ''; //否,String(128),订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。时区为GMT+8 beijing。该时间取自商户服务器
            $time_expire = $data['time_expire'] ?? ''; //否,String(14),订单超时时间
            $goods_tag = $data['goods_tag'] ?? ''; //否,String(32),商品标记，微信平台配置的商品标记，用于优惠券或者满减使用
            $detail = $data['detail'] ?? ''; //否,String(6000),单品优惠活动该字段必传，且必须按照规范上传，JSON格式
//            商品编码,goods_id,是,String(32)
//            商品名称,goods_name,是,String(256)
//            商品数量,quantity,是,Number,商品数量,可为整型或浮点型
//            商品单价,price,是,Int,以分为单位，不允许包含任何字、符号
//            [
//                {
//                    "goods_id":" 商 品 编 码 ",
//                    "goods_name":"HUAWEI P30",
//                    "quantity":1,
//                    "price":528800
//                },
//                {
//                    "goods_id":" 商 品 编 码 ",
//                    "goods_name":"iPhone6s 32G",
//                    "quantity":1,
//                    "price":608800
//                }
//            ]
            $limit_pay = $data['limit_pay'] ?? ''; //否,String(32),no_credit--指定不能使用信用卡支付
            $product_id = $data['product_id'] ?? ''; //否,String(32),预留字段此id为静态可打印的二维码中包含的商品ID，商户自行维护
            $member_mobile = $data['member_mobile'] ?? ''; //否,String(16),会员手机号,与会员卡号任选其一
            $member_card_id = $data['member_card_id'] ?? ''; //否,String(64),会员卡号,与会员手机号任选其一

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            $pay_method = 'qr_code';

            //刷脸处理
            $strlen = strlen($auth_code);
            if ($strlen > 18) {
                $substr = substr($auth_code, -1); //截取判断最后一个
                $auth_code = substr($auth_code, 0, -1); //去掉最后一个
                $str = substr($auth_code, 0, 2);

                //支付宝刷脸
                if ($substr == '2' && in_array($str, ['28'])) {
                    $pay_method = 'alipay_face';
                }

                //微信刷脸
                if ($substr == '2' && in_array($str, ['13', '14'])) {
                    $pay_method = 'weixin_face';
                }
            }

            //调用系统前参数
            $ro_data = [
                'store_id' => $store_id, //
                'code' => $auth_code,
                'total_amount' => $total_fee / 100,
                'shop_price' => $total_fee / 100,
                'qwx_no' => $out_trade_no, //
                'remark' => '', //
                'device_id' => $device_id, //
                'shop_name' => '商品',
                'shop_desc' => $body ?? '商品',
                'pay_method' => $pay_method
            ];
//            if ($out_trade_no) $ro_data['out_trade_no'] = $out_trade_no;
            if ($merchant_id) $ro_data['merchant_id'] = $merchant_id;
            if ($merchant_name) $ro_data['merchant_name'] = $merchant_name;

            //发起交易
            $order = new TradepayTwoController();
            $tra_data = $order->scan_pay($ro_data);
            $tra_data_arr = json_decode($tra_data, true);
//            Log::info('收钱啦-被扫-结果');
//            Log::info($tra_data_arr);
            $out_transaction_id = '';
            $time_end = '';
            $re_data = [
                'version' => '1.0.0', //版本号,
                'charset' => 'UTF-8', //字符集
                'sign_type' => 'MD5', //签名类型，取值：MD5
                'appid' => $appid, //String(32),我方支付分配的应用ID
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串，不长于32位
                'return_code' => 'SUCCESS', //SUCCESS/FAIL。此字段是通信标识，非交易标识，交易是否成功需要查看 result_code 来判断
                'device_info' => $device_id, //
//                'return_msg' => '', //返回信息，如非空，为错误原因
                'result_code' => 'SUCCESS', //String(16),SUCCESS/FAIL
                'sign' => '', //String(32),MD5签名结果
//                'err_code' => '', //否,String(32),参考错误码
//                'err_code_des' => '', //否,String(128),结果信息描述
                'need_query' => 'N', //否,String(32),用来判断是否需要调用查询接口，值为Y或空时需要，值为N时不需要
            ];

            //用户支付成功
            if ($tra_data_arr['status'] == 1) {
                //微信，支付宝支付凭证
                $out_transaction_id = isset($tra_data_arr['data']['out_transaction_id']) ? $tra_data_arr['data']['out_transaction_id'] : "";

                //快钱微信处理
                $mybank_weixin = substr($out_transaction_id, 0, 4);
                if ($mybank_weixin == "MYBK") {
                    $out_transaction_id = strtolower($out_transaction_id); //大写转小写
                }

                $trade_type = '';
                $ways_source = isset($tra_data_arr['data']['ways_source'])? $tra_data_arr['data']['ways_source']:'';
                if ($ways_source) {
                    if ($ways_source == 'alipay') $trade_type = 'pay.alipay.micropay';
                    if ($ways_source == 'weixin') $trade_type = 'pay.weixin.micropay';
                    if ($ways_source == 'unionpay') $trade_type = 'pay.qpass.micropay';
                }

                if (isset($tra_data_arr['data']['pay_time'])) $time_end = date('YMDHis', strtotime($tra_data_arr['data']['pay_time']));

                $re_data['out_transaction_id'] = $out_transaction_id; //String(32),平台交易单号
                $re_data['mch_transaction_id'] = isset($tra_data_arr['data']['trade_no']) ? $tra_data_arr['data']['trade_no']: $out_transaction_id; //String(32),通道订单号，32个字符内、可包含字母
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no']; //String(32),商户系统内部的订单号，32个字符内、可包含字母
                $re_data['total_fee'] = $tra_data_arr['data']['total_amount']*100; //Int,总金额，以分为单位，不允许包含任何字、符号
                $re_data['trade_type'] = $trade_type; //String(16),pay.weixin.micropay:微信刷卡支付 pay.alipay.micropay:支付宝刷卡支付 pay.qpass.micropay:云闪付刷卡支付
                $re_data['time_end'] = $time_end ?? date('YMDHis', time()); //String(14),支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。时区为GMT+8 beijing。该时间取自我方服务器
//                $re_data['member_mobile'] = ''; //否,String(16),会员手机号
//                $re_data['member_card_id'] = ''; //否,String(64),会员卡号
//                $re_data['member_score'] = ''; //否,int,本次积分
//                $re_data['member_total_score'] = ''; //否,int,总积分
            } //其他错误
            else {
                $data['result_code'] = 'FAIL'; //String(16),SUCCESS/FAIL
                $data['appid'] = $appid; //String(32),我方支付分配的应用ID
//                $data['sign'] = ''; //String(32),MD5签名结果
                $data['nonce_str'] = $this->nonceStr(); //String(32),随机字符串，不长于32位
                $re_data['result_code'] = 'FALL';
//                $re_data['err_code'] = '; //错误代码
//                $re_data['err_code_des'] = '; //错误代码描述
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            Log::info('收钱啦-扫一扫收款error');
            Log::info($exception->getMessage() .' | '.$exception->getFile().' | '. $exception->getLine());
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() .' | '. $exception->getLine()
            ];
            return $this->return_data($err);
        }
    }

    /**
     * 查询订单
     *
     * 需要调用查询接口的情况：
     * 当商户后台、网络、服务器等出现异常，商户系统最终未接收到支付通知；
     * 调用支付接口后，返回系统错误或未知交易状态情况；
     * 调用关单或撤销接口API之前，需确认支付状态
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function order_query($data)
    {
        try {
//            Log::info('收钱啦-订单号查询-入参');
//            Log::info($data);

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = isset($data['device_id']) ? $data['device_id']: ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : ''; //否,String(32),商户订单号
            $mch_transaction_id = isset($data['mch_transaction_id']) ? $data['mch_transaction_id'] : ''; //否,String(32),第三方平台交易号
            $transaction_id = isset($data['transaction_id']) ? $data['transaction_id'] : ''; //否,String(32),平台交易号,out_trade_no和transaction_id至少一个必填，同时存在时transaction_id优先

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
            }

            //如果订单号为空或者不存在
            if (!$order) {
                Log::info('收钱啦-查询订单-无果：');
                Log::info($out_trade_no);
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }

            $out_transaction_id = '';
            $time_end = '';
            $trade_no = $order->trade_no;

            $re_data = [
                'version' => '1.0.0',
                'charset' => 'UTF-8',
                'sign_type' => 'MD5',
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
//                'return_msg' => '', //否,String(128),返回信息如非空为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //业务结果,SUCCESS/FAIL
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串
//                'err_code' => '', //否,String(32),错误代码
//                'err_code_des' => '', //否,String(128),错误代码描述
            ];

            $type = $order->ways_type;
            $out_trade_no = $order->out_trade_no;
            $store_obj = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid')
                ->first();
            $config_id = $store_obj->config_id;
            $store_pid = $store_obj->pid;

            //官方支付宝查询
            if (999 < $type && $type < 1999) {
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid);
                $config = $isvconfig->AlipayIsvConfig($config_id);

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.query';
                $requests = new AlipayTradeQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"" .
                    "  }");
                $status = $aop->execute($requests, '', $storeInfo->app_auth_token);
                //支付成功
                if ($status->alipay_trade_query_response->trade_status == "TRADE_SUCCESS") {
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.alipay.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = isset($status->alipay_trade_query_response->send_pay_date) ? date('YmdHis', strtotime($status->alipay_trade_query_response->send_pay_date)) : ''; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $status->alipay_trade_query_response->buyer_user_id,
                            'trade_no' => $status->alipay_trade_query_response->trade_no,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,

                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '1000', //返佣来源
                            'source_desc' => '支付宝', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    return $this->return_data($re_data);
                } //等待付款
                elseif ($status->alipay_trade_query_response->trade_status == "WAIT_BUYER_PAY") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单关闭
                elseif ($status->alipay_trade_query_response->trade_status == 'TRADE_CLOSED') {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $status->alipay_trade_query_response->sub_msg;
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //直付通
            if (16000 < $type && $type < 16999) {
                $config_type = '03';
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.query';
                $requests = new AlipayTradeQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"" .
                    "  }");
                $status = $aop->execute($requests, '', '');
                //支付成功
                if ($status->alipay_trade_query_response->trade_status == "TRADE_SUCCESS") {
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.alipay.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['appid'] = $config->app_id; //String(32),服务商公众号appid
                    $re_data['openid'] = $order->user_id; //String(128),用户在服务商appid下的唯一标识
                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = isset($status->alipay_trade_query_response->send_pay_date) ? date('YmdHis', strtotime($status->alipay_trade_query_response->send_pay_date)) : ''; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $status->alipay_trade_query_response->buyer_user_id,
                            'trade_no' => $status->alipay_trade_query_response->trade_no,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '16000', //返佣来源
                            'source_desc' => '支付宝', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'pay_time' => $status->alipay_trade_query_response->send_pay_date,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

//                    return $this->return_data($re_data);
                } //等待付款
                elseif ($status->alipay_trade_query_response->trade_status == "WAIT_BUYER_PAY") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单关闭
                elseif ($status->alipay_trade_query_response->trade_status == 'TRADE_CLOSED') {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
                else {
                    //其他情况
                    $message = $status->alipay_trade_query_response->sub_msg;
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //官方微信查询
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;

                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], //XXX: 绝对路径！
                    'key_path' => $options['payment']['key_path'],     //XXX: 绝对路径！
                    'sub_mch_id' => $wx_sub_merchant_id,
                    // 'device_info'     => '013467007045764',
                    // 'sub_app_id'      => ''
                ];
                $payment = Factory::payment($config);
                $query = $payment->order->queryByOutTradeNumber($order->out_trade_no);
                //成功
                if ($query['trade_state'] == 'SUCCESS') {
                    //删除商品
                    if ($weixin_store->wx_shop_id && Schema::hasTable('shops')) {
                        Shop::where('store_id', $store_id)
                            ->where('merchant_id', $order->merchant_id)
                            ->delete();
                    }

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 'TRADE_SUCCESS',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => $query['openid'],
                            'trade_no' => $query['transaction_id'],
                            'pay_time' => date('Y-m-d H:i:s', strtotime($query['time_end']))
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '2000', //返佣来源
                            'source_desc' => '微信支付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'company' => $order->company,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => date('Y-m-d H:i:s', strtotime($query['time_end'])),
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.weixin.jspay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = $query['time_end']; //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型

//                    return $this->return_data($re_data);
                }
                elseif ($query['trade_state'] == "USERPAYING") {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
                else {
                    //其他情况
                    $message = $query['trade_state_desc'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                }
            }

            //京东收银支付
            if (5999 < $type && $type < 6999) {
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $return = $obj->order_query($data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['tradeNo'];
                        $channelNoSeq = isset($return['data']['channelNoSeq']) ? $return['data']['channelNoSeq'] : $trade_no; //条码
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['payFinishTime']));
                        $buyer_pay_amount = $return['data']['piAmount'] / 100;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $channelNoSeq,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '6000', //返佣来源
                            'source_desc' => '京东金融', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = 'pay.qpass.micropay'; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $out_transaction_id ?? ''; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //快钱支付
            if (2999 < $type && $type < 3999) {
                //读取配置
                $MyBankobj = new MyBankConfigController();
                $mybank_merchant = $MyBankobj->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $MerchantId = $mybank_merchant->MerchantId;
                $wx_AppId = $mybank_merchant->wx_AppId;

                $MyBankConfig = $MyBankobj->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new TradePayController();
                $return = $obj->mybankOrderQuery($MerchantId, $config_id, $order->out_trade_no);
                if ($return['status'] == 0) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = $return['message'];
                    return $this->return_data($re_data);
                }
                $body = $return['data']['document']['response']['body'];
                $TradeStatus = $body['TradeStatus'];

                //成功
                if ($TradeStatus == 'succ') {
                    $OrderNo = $body['MerchantOrderNo'];
                    $GmtPayment = $body['GmtPayment'];
                    $buyer_id = '';
                    $trade_type = '';

                    if ($type == 3001) {
                        $trade_type = 'pay.alipay.jspay';
                    }
                    if ($type == 3002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 3003) {
                        $buyer_id = $body['BuyerUserId'];
                        $trade_type = 'pay.qpass.micropay';
                    }
                    if ($type == 3004) {
                        $buyer_id = $body['SubOpenId'];
                        $trade_type = 'pay.qpass.micropay';
                    }

                    $pay_time = date('Y-m-d H:i:s', strtotime($GmtPayment));
                    $payment_method = strtolower($body['Credit']);

                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => 1,
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_id' => $buyer_id,
                            'trade_no' => $OrderNo,
                            'pay_time' => $pay_time,
                            'payment_method' => $payment_method,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '3000', //返佣来源
                            'source_desc' => '快钱', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $OrderNo ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($GmtPayment)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                elseif ($TradeStatus == 'paying') {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = '请重新扫码';
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //新大陆收银支付
            if (7999 < $type && $type < 8999) {
                //读取配置
                $config = new NewLandConfigController();
                $new_land_config = $config->new_land_config($config_id);
                if (!$new_land_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '新大陆配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $new_land_merchant = $config->new_land_merchant($store_id, $store_pid);
                if (!$new_land_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $request_data = [
                    'out_trade_no' => $order->out_trade_no,
                    'key' => $new_land_merchant->nl_key,
                    'org_no' => $new_land_config->org_no,
                    'merc_id' => $new_land_merchant->nl_mercId,
                    'trm_no' => $new_land_merchant->trmNo,
                    'op_sys' => '3',
                    'opr_id' => $store_obj->merchant_id,
                    'trm_typ' => 'T'
                ];
                $obj = new PayController();
                $return = $obj->order_query($request_data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['orderNo'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['sysTime']));
                        $buyer_pay_amount = $return['data']['amount'] / 100;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '8000', //返佣来源
                            'source_desc' => '新大陆', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            // 'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 8001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 8002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 8003 || $type == 8004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $transaction_id ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['amount']; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['sysTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }//订单退款
                elseif ($return["status"] == 4) {
                    $message = '订单已经退款';
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //和融通收银支付
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['md_key'] = $h_config->md_key; //
                $data['mid'] = $h_merchant->h_mid; //
                $data['orgNo'] = $h_config->orgNo; //

                $return = $obj->order_query($data);

                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['transactionId'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['timeEnd']));
                        $buyer_pay_amount = $return['data']['totalFee'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '9000', //返佣来源
                            'source_desc' => '和融通', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 9001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 9002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 9003 || $type == 9004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $return['data']['transactionId'] ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['totalFee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['timeEnd'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
            }

            //联拓富收银支付
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();
                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['outTransactionId'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['payTime']));
                        $buyer_pay_amount = $return['data']['receiptAmount'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');



                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];

                        $this->update_day_order($insert_data, $out_trade_no);


                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '10000', //返佣来源
                            'source_desc' => '联拓覆', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'fee_amount' => $order->fee_amount,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报

                        ];


                        PaySuccessAction::action($data);

                    }

                    $trade_type = '';
                    if ($type == 10001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 10002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 10003 || $type == 10004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $return['data']['transactionId'] ?? $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['totalFee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['payTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'NOTPAY'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //随行付支付
            if (12999 < $type && $type < 13999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付配置不存在请检查配置';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付配置不存在请检查配置'
//                    ]);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付商户号不存在';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付商户号不存在'
//                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/pay_notify_url'); //回调地址
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['respData']['sxfUuid'];
                        $buyer_pay_amount = $return['data']['respData']['oriTranAmt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '13000', //返佣来源
                            'source_desc' => '随行付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 13001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 13002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 13003 || $type == 13004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $return['data']['respData']['sxfUuid'] ?? $order->out_trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['respData']['oriTranAmt']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['respData']['tranTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
//                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
//                    return $this->return_data($re_data);
                }
            }

            //随行付A支付
            if (18999 < $type && $type < 19999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbilla_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付a支付未配置';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付配置不存在请检查配置'
//                    ]);
                }

                $vbill_merchant = $config->vbilla_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '随行付a商户号不存在';
                    return $this->return_data($re_data);
//                    return json_encode([
//                        'status' => 2,
//                        'message' => '随行付商户号不存在'
//                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/pay_notify_a_url'); //回调地址
                $data['request_url'] = $obj->order_query_url; //请求地址
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->order_query($data);
//                Log::info('收钱啦-随行付a-订单查询结果：');
//                Log::info($return["status"]);
                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['respData']['tranTime']));
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['respData']['sxfUuid'];
                        $buyer_pay_amount = $return['data']['respData']['oriTranAmt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '19000', //返佣来源
                            'source_desc' => '随行付A', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 19001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 19002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $query['openid']; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 19003 || $type == 19004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $return['data']['respData']['sxfUuid'] ?? $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['respData']['oriTranAmt']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['respData']['tranTime'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
//                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
//                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
//                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
//                    return $this->return_data($re_data);
                }
            }

            //哆啦宝支付
            if (14999 < $type && $type < 15999) {
                $manager = new ManageController();
                $dlbconfig = $manager->pay_config($config_id);
                if (!$dlbconfig) {
                    return json_encode([
                        'status' => 2,
                        'message' => '哆啦宝配置配置不存在请检查配置'
                    ]);
                }

                $dlb_merchant = $manager->dlb_merchant($store_id, $store_pid);
                if (!$dlb_merchant && !empty($dlb_merchant->mch_num) && !empty($dlb_merchant->shop_num)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '哆啦宝配置商户未补充商户编号等信息!'
                    ]);
                }

                $query_data = [
                    'agentNum' => $dlbconfig->agent_num,
                    'customerNum' => $dlb_merchant->mch_num,
                    'shopNum' => $dlb_merchant->shop_num,
                    'requestNum' => $order->out_trade_no,
                    'secretKey' => $dlbconfig->secret_key,
                    'accessKey' => $dlbconfig->access_key,
                ];
                $return = $manager->query_bill($query_data);
                if ($return['status'] == 1) {
                    $query_result = $return['data'];
                    if ($query_result['status'] == "SUCCESS") {
                        try {
                            $pay_time = $query_result['completeTime'];
                            $trade_no = $query_result['orderNum'];
                            $buyer_pay_amount = $query_result['orderAmount'];
                            $buyer_id = isset($query_result['openId']) ? $query_result['openId'] : "";

                            //改变数据库状态
                            if ($order->pay_status != 1) {

                                $insert_data = [
                                    'status' => '1',
                                    'pay_status' => 1,
                                    'pay_status_desc' => '支付成功',
                                    'buyer_id' => $buyer_id,
                                    'trade_no' => $trade_no,
                                    'pay_time' => $pay_time,
                                    'buyer_pay_amount' => $buyer_pay_amount,
                                ];
                                $this->update_day_order($insert_data, $out_trade_no);

                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '15000', //返佣来源
                                    'source_desc' => '哆啦宝', //返佣来源说明
                                    'company' => $order->company, //
                                    'fee_amount' => $order->fee_amount, //
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'rate' => $order->rate,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $pay_time,
                                    'device_id' => isset($order->device_id) ? $order->device_id : "",

                                ];


                                PaySuccessAction::action($data);

                            }

                            $trade_type = '';
                            if ($type == 15001) $trade_type = 'pay.alipay.jspay';
                            if ($type == 15002) {
                                $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                            }
                            if ($type == 15003 || $type == 15004) $trade_type = 'pay.qpass.micropay';
                            $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                            //trade_state为success
                            $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                            $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                            $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                            $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                            $re_data['total_fee'] = $query_result['orderAmount']*100; //int,总金额，以分为单位
                            $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                            $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                            $re_data['bank_type'] = ''; //String(16),银行类型
                        } catch (\Exception $e) {
                            $message = '订单查询失败' . $e->getLine() . $e->getMessage();
                            $re_data['result_code'] = 'FALL';
                            $re_data['result_msg'] = $message;
                            $re_data['outTradeNo'] = $order->qwx_no;
                        }
                    }
                    elseif ($query_result['status'] == "INIT") {
                        $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    }
                    elseif ($query_result['status'] == "CANCEL") {
                        $re_data['trade_state'] = 'CLOSED';
                    }
                    elseif ($query_result['status'] == "REFUND") {
                        $message = '订单已经退款';
                        $re_data['trade_state'] = 'REFUND';
                        return $this->return_data($re_data);
                    }
                    elseif ($query_result['status'] == "REFUNDING") {
                        $message = '订单退款中';
                        $re_data['trade_state'] = 'REFUND';
                    }
                    elseif ($query_result['status'] == "FUNDFAIL") {
                        $message = '订单退款失败';
                        $re_data['trade_state'] = 'PAYERROR';
                    }
                    else {
                        $message = '订单退款失败';
                        $re_data['trade_state'] = 'PAYERROR';
                    }
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                }
            }

            //传化收银支付
            if (11999 < $type && $type < 12999) {
                //读取配置
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['channel_no'];
                        $pay_time = date('Y-m-d H:i:s', strtotime($return['data']['paid_at']));
                        $buyer_pay_amount = $return['data']['total_fee'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '12000', //返佣来源
                            'source_desc' => 'TF', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 12001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 12002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 12003 || $type == 12004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['total_fee']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['paid_at'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //工行收银支付
            if (19999 < $type && $type < 20999) {
                $config = new LianfuConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['out_trade_no'] = $out_trade_no; //
                $return = $obj->order_query($data);
//                Log::info('收钱啦-工行查询');
//                Log::info($return);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = isset($return['data']['tp_order_id'])?$return['data']['tp_order_id']:$out_trade_no;
                        $pay_time = date('Y-m-d H:i:s', time());
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '20200', //返佣来源
                            'source_desc' => 'lianfu', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 20001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 20002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 20003 || $type == 20004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', time()); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                }//订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //海科融通 交易查询
            if (21999 < $type && $type < 22999) {
                //读取配置
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通配置不存在请检查配置'
                    ]);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_data = [
                    'trade_no' => $order->trade_no, //trade_no和out_trade_no和channel_trade_no必传其中一个，三个都传则以trade_no为准，推荐使用trade_no
                    'out_trade_no' => $order->out_trade_no, //服务商的交易订单编号
                    'channel_trade_no' => '', //凭证条码订单号
                    'access_id' => $hkrt_config->access_id,
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('海科融通-收钱啦-交易查询-入参');
//                Log::info($hkrt_data);
                $return = $obj->order_query($hkrt_data); //0-系统错误 1-交易成功；2-交易失败；3-交易进行中；4-交易超时
//                Log::info('海科融通-收钱啦-交易查询-结果');
//                Log::info($return);

                //支付成功
                if ($return["status"] == 1) {
                    $pay_time = $return['data']['trade_end_time'];
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = $return['data']['trade_no'];
                        $buyer_pay_amount = $return['data']['total_amount'];


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '22000', //返佣来源
                            'source_desc' => '海科融通', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 22001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 22002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 22003 || $type == 22004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $return['data']['total_amount']*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //交易进行中
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }//交易超时
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //易生支付 交易查询
//            if (20999 < $type && $type < 21999) {
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }
                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付配置不存在请检查配置'
                    ]);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\EasyPay\PayController();
                $easypay_data = [
                    'channel_id' => $easypay_config->channel_id, //渠道编号
                    'mer_id' => $easypay_merchant->termMercode, //终端商户编号
                    'device_id' => $easypay_merchant->termTermcode, //终端编号
                    'out_trade_no' => $order->out_trade_no, //原交易流水
                    "private_key"=>$easypay_config->private_key
                ];
//                Log::info('易生支付-收钱啦-交易查询-入参');
//                Log::info($easypay_data);
                $return = $obj->order_query($easypay_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//                Log::info('易生支付-收钱啦-交易查询-结果');
//                Log::info($return);

                $pay_time = isset($return['data']['wxtimeend']) ? date('Y-m-d H:i:s', strtotime($return['data']['wxtimeend'])): ''; //支付完成时间，格式为 yyyyMMddhhmmss
                $trade_no = $return['data']['wtorderid'] ?? ''; //系统订单号
                $buyer_pay_amount = isset($return['data']['payamt']) ? ($return['data']['payamt'] / 100): ''; //实付金额，单位分
                $buyer_id = $return['data']['wxopenid'] ?? ''; //用户在商户 appid 下的唯一标识(微信/支付宝渠道返回)

                //支付成功
                if ($return['status'] == '1') {
                    //改变数据库状态
                    if ($order->pay_status != '1') {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => '1',
                            'pay_status_desc' => '支付成功',
                            'buyer_id' => $buyer_id,
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '21000', //返佣来源
                            'source_desc' => '易生支付', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 21001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 21002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 21003 || $type == 21004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = isset($return['data']['payamt']) ? $return['data']['payamt']: $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($return['data']['wxtimeend'])); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //交易进行中
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
                //交易超时
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //邮政收银支付
            if (26000 < $type && $type < 26999) {
                $config = new LianfuyoupayConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfuyouzheng\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['pos_sn'] = $h_merchant->pos_sn;
                $data['goods_name'] = '商品'; //

                $return = $obj->order_query($data);
                //支付成功
                if ($return["status"] == 1) {
                    //改变数据库状态
                    if ($order->pay_status != 1) {
                        $trade_no = isset($return['data']['tp_order_id'])?$return['data']['tp_order_id']:$out_trade_no;
                        $pay_time = date('Y-m-d H:i:s', time());
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');


                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '26000', //返佣来源
                            'source_desc' => 'lianfuyoupay', //返佣来源说明
                            'total_amount' => $order->total_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'fee_amount' => $order->fee_amount,
                            'pay_time' => $pay_time,
                            'no_push' => '1', //不推送
                            'no_fuwu' => '1', //不服务消息
                            'no_print' => '1', //不打印
                            //'no_v' => '1', //不小盒子播报
                        ];
                        PaySuccessAction::action($data);
                    }

                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['result_msg'] = '支付成功';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    $re_data['out_transaction_id'] = $trade_no; //$query['transaction_id'];
                    $re_data['time_end'] = date('YmdHis', time());

                    $trade_type = '';
                    if ($type == 26001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 26002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 26003 || $type == 26004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', time()); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                } //订单退款
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'REFUND';
                    return $this->return_data($re_data);
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //葫芦天下
            if (22999 < $type && $type < 23999) {
                $manager = new \App\Api\Controllers\Hltx\ManageController();
                $hltx_merchant = $manager->pay_merchant($store_id, $store_pid);
                $qd = $hltx_merchant->qd;

                $hltx_config = $manager->pay_config($config_id, $qd);
                if (!$hltx_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => 'HL支付配置不存在请检查配置'
                    ]);
                }

                $manager->init($hltx_config);

                switch ($type) {
                    case 23001:
                        $pay_channel = 'ALI';
                        break;
                    case 23002:
                        $pay_channel = 'WX';
                        break;
                    case 23004:
                        $pay_channel = 'UPAY';
                        break;
                    default:
                        $pay_channel = 'ALI';
                        break;
                }

                if (!$hltx_merchant || empty($hltx_merchant->mer_no)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户未成功开通HL通道!'
                    ]);
                }

                $hltx_data = [
                    'merNo' => $hltx_merchant->mer_no,
                    'orderNo' => $order->out_trade_no
                ];
                $return = $manager->query_order($hltx_data);
                if ($return['status'] == 1) {
                    $return = $return['data'];
                    if ($return['tradeStatus'] == "S") {
                        if ($return['subTradeStatus'] == 'COMPLETE') {
                            try {
                                $pay_time = $return['payCompleteTime'];
                                $trade_no = $return['transIndex'];
                                $buyer_pay_amount = $return['amount'] / 100;
                                //改变数据库状态
                                if ($order->pay_status != 1) {

                                    $insert_data = [
                                        'status' => '1',
                                        'pay_status' => 1,
                                        'pay_status_desc' => '支付成功',
                                        'buyer_logon_id' => '',
                                        'trade_no' => $trade_no,
                                        'pay_time' => $pay_time,
                                        'buyer_pay_amount' => $buyer_pay_amount,
                                    ];
                                    $this->update_day_order($insert_data, $out_trade_no);

                                    //支付成功后的动作
                                    $data = [
                                        'ways_type' => $order->ways_type,
                                        'ways_type_desc' => $order->ways_type_desc,
                                        'source_type' => '23000', //返佣来源
                                        'source_desc' => 'HL', //返佣来源说明
                                        'company' => 'hltx', //返佣来源说明
                                        'total_amount' => $order->total_amount,
                                        'out_trade_no' => $order->out_trade_no,
                                        'rate' => $order->rate,
                                        'merchant_id' => $order->merchant_id,
                                        'store_id' => $order->store_id,
                                        'user_id' => $order->user_id,
                                        'config_id' => $config_id,
                                        'store_name' => $order->store_name,
                                        'ways_source' => $order->ways_source,
                                        'pay_time' => $pay_time,
                                        'device_id' => isset($order->device_id) ? $order->device_id : "",
                                    ];
                                    PaySuccessAction::action($data);
                                }

                                $trade_type = '';
                                if ($type == 23001) $trade_type = 'pay.alipay.jspay';
                                if ($type == 23002) {
                                    $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                                }
                                if ($type == 23003 || $type == 23004) $trade_type = 'pay.qpass.micropay';
                                $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                                //trade_state为success
                                $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                                $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                                $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                                $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                                $re_data['total_fee'] = $return['amount']; //int,总金额，以分为单位
                                $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                                $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                                $re_data['bank_type'] = ''; //String(16),银行类型
                            } catch (\Exception $e) {
                                $message = '订单查询失败' . $e->getLine() . $e->getMessage();
                                $re_data['result_code'] = 'FALL';
                                $re_data['result_msg'] = $message;
                                $re_data['outTradeNo'] = $order->qwx_no;
                            }
                        } //订单支付失败
                        elseif (in_array($return['subTradeStatus'], ['FAILED', 'SYS_FAILED', 'CANCEL', 'CLOSE'])) {
                            $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                        } //等待用户付款
                        else {
                            $re_data['trade_state'] = 'USERPAYING';
                        }
                    } //订单支付失败
                    elseif ($return['tradeStatus'] == "E") {
                        $re_data['trade_state'] = 'PAYERROR';
                    } //等待用户付款
                    else {
                        $re_data['trade_state'] = 'USERPAYING';
                    }
                } //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                }
            }

            //联动优势 交易查询
            if (4999 < $type && $type < 5999) {
                $config = new LinkageConfigController();
                $linkage_config = $config->linkage_config($config_id);
                if (!$linkage_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '联动优势支付配置不存在请检查配置'
                    ]);
                }

                $linkage_merchant = $config->linkage_merchant($store_id, $store_pid);
                if (!$linkage_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '联动优势商户号不存在'
                    ]);
                }

                $obj = new LinkagePayController();
                $linkage_data = [
                    'acqSpId' => $linkage_config->mch_id, //代理商编号
                    'privateKey' => $linkage_config->privateKey, //
                    'publicKey' => $linkage_config->publicKey, //
                    'acqMerId' => $linkage_merchant->acqMerId, //商户号
                    'trade_no' => $order->trade_no, //联动优势的订单号，建议优先使用
                    'out_trade_no' => $out_trade_no //商户订单号
                ];
//                Log::info('联动优势-收钱啦-交易查询');
//                Log::info($linkage_data);
                $return = $obj->order_query($linkage_data); //-1系统错误；0-其他；1-交易成功；2-验签失败；3-转入退款；4-交易结果未明；5-已关闭；6-已撤销(付款码支付)；7-明确支付失败
//                Log::info($return);

                if ($return['status'] == '1') { //支付成功
                    $pay_time = isset($return['data']['payTime']) ? date('Y-m-d H:i:s', strtotime(substr($return['data']['platDate'], 0, 4).$return['data']['payTime'])): ''; //交易时间 格式：MMDDhhmmss
                    $trade_no = $return['data']['transactionId']; //联动优势的流水号
                    $buyer_pay_amount = isset($return['data']['txnAmt']) ? ($return['data']['txnAmt']/100): $order->total_amount; //订单金额 (打印小票使用)
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $paySeq = $return['data']['paySeq'] ?? ''; //支付流水号（条形码），成功返回
                    $depBankSeq = $return['data']['depBankSeq'] ?? ''; //第三方流水号（微信/支付宝/银联的交易流水号）

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'auth_code' => $paySeq,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '5000', //返佣来源
                            'source_desc' => '联动优势', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 5001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 5002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 5003 || $type == 5004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //退款
                elseif ($return["status"] == 3) {
                    $re_data['trade_state'] = 'REFUND'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易关闭
                elseif ($return["status"] == 5) {
                    $re_data['trade_state'] = 'CLOSED';
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 7) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //威富通 交易查询
            if (26999 < $type && $type < 27999) {
                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $config = new WftPayConfigController();
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付配置不存在请检查配置'
                    ]);
                }

                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通商户号不存在'
                    ]);
                }

                $obj = new WftPayPayController();
                $wftpay_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通-收钱啦-交易查询-入参');
//                Log::info($wftpay_data);
                $return = $obj->order_query($wftpay_data); //0-系统错误 1-成功 2-失败 3-转入退款 4-未支付 5-已关闭 6-已冲正 7-已撤销 8-用户支付中
//                Log::info('威富通-收钱啦-交易查询');
//                Log::info($return);

                if ($return['status'] == 1) {
                    $pay_time = $return['data']['time_end'] ? date('Y-m-d H:i:s', strtotime($return['data']['time_end'])): ''; //支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010
                    $trade_no = $return['data']['transaction_id']; //平台交易号
                    $buyer_pay_amount = $return['data']['total_fee'] ? ($return['data']['total_fee']/100): $order->total_amount; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '27000', //返佣来源
                            'source_desc' => '威富通', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 27001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 27002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 27003 || $type == 27004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //用户支付中
                elseif ($return["status"] == 8) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //交易失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
                //未支付
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'NOTPAY';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            //汇旺财 交易查询
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付配置不存在请检查配置'
                    ]);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财商户号不存在'
                    ]);
                }

                $obj = new HwcPayPayController();
                $hwcpay_data = [
                    'mch_id' => $hwcpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财-收钱啦-交易查询-入参');
//                Log::info($hwcpay_data);
                $return = $obj->order_query($hwcpay_data); //0-系统错误 1-成功 2-失败 3-转入退款 4-未支付 5-已关闭 6-已冲正 7-已撤销 8-用户支付中
//                Log::info('汇旺财-收钱啦-交易查询');
//                Log::info($return);

                if ($return['status'] == 1) {
                    $pay_time = $return['data']['time_end'] ? date('Y-m-d H:i:s', strtotime($return['data']['time_end'])): ''; //支付完成时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010
                    $trade_no = isset($return['data']['third_order_no']) ? $return['data']['third_order_no'] : $return['data']['transaction_id']; //平台交易号
                    $buyer_pay_amount = $return['data']['total_fee'] ? ($return['data']['total_fee']/100): ''; //总金额，以分为单位，不允许包含任何字、符号
                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                    $depBankSeq = $return['data']['out_transaction_id'] ?? ''; //第三方交易号

                    //改变数据库状态
                    if ($order->pay_status != 1) {

                        $insert_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'buyer_logon_id' => '',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'other_no' => $depBankSeq
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        //支付成功后的动作
                        $data = [
                            'ways_type' => $order->ways_type,
                            'company' => $order->company,
                            'ways_type_desc' => $order->ways_type_desc,
                            'source_type' => '28000', //返佣来源
                            'source_desc' => '汇旺财', //返佣来源说明
                            'total_amount' => $buyer_pay_amount,
                            'out_trade_no' => $order->out_trade_no,
                            'rate' => $order->rate,
                            'fee_amount' => $order->fee_amount,
                            'merchant_id' => $order->merchant_id,
                            'store_id' => $order->store_id,
                            'user_id' => $order->user_id,
                            'config_id' => $config_id,
                            'store_name' => $order->store_name,
                            'ways_source' => $order->ways_source,
                            'pay_time' => $pay_time,
                            'device_id' => isset($order->device_id) ? $order->device_id : "",
                        ];
                        PaySuccessAction::action($data);
                    }

                    $trade_type = '';
                    if ($type == 28001) $trade_type = 'pay.alipay.jspay';
                    if ($type == 28002) {
                        $trade_type = 'pay.weixin.jspay';
//                    $re_data['appid'] = $options['app_id']; //String(32),服务商公众号appid
//                    $re_data['openid'] = $buyer_id; //String(128),用户在服务商appid下的唯一标识
//                    $re_data['is_subscribe'] = 'N'; //String(128),用户是否关注服务商公众账号，Y-关注，N-未关注
                    }
                    if ($type == 28003 || $type == 28004) $trade_type = 'pay.qpass.micropay';
                    $re_data['trade_state'] = 'SUCCESS'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    //trade_state为success
                    $re_data['trade_type'] = $trade_type; //pay.weixin.micropay:微信刷卡支付;pay.alipay.micropay:支付宝刷卡支付;pay.qpass.micropay:云闪付刷卡支付;pay.weixin.jspay:微信JSAPI支付;pay.alipay.jspay：支付宝APP支付
                    $re_data['transaction_id'] = $order->qwx_no; //String(32),平台交易单号
                    $re_data['out_transaction_id'] = $trade_no; //否,String(32),第三方订单号（支付成功后会返回，没支付则不会）
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['total_fee'] = $buyer_pay_amount*100; //int,总金额，以分为单位
                    $re_data['time_end'] = date('YmdHis', strtotime($pay_time)); //String(128),订单支付时间
                    $re_data['fee_type'] = 'CNY'; //String(8),货币类型，符合ISO4217标准的三位字母代码，默认人民币：CNY
                    $re_data['bank_type'] = ''; //String(16),银行类型
                }
                //用户支付中
                elseif ($return["status"] == 8) {
                    $re_data['trade_state'] = 'USERPAYING'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //订单支付失败
                elseif ($return["status"] == 2) {
                    $re_data['trade_state'] = 'PAYERROR'; //SUCCESS—支付成功;REFUND—转入退款;USERPAYING-用户支付中;NOTPAY—未支付;CLOSED—已关闭;REVOKED-已撤消;PAYERROR—支付失败(其他原因，如银行返回失败)
                    return $this->return_data($re_data);
                }
                //未支付
                elseif ($return["status"] == 4) {
                    $re_data['trade_state'] = 'NOTPAY';
                    return $this->return_data($re_data);
                }
                //其他情况
                else {
                    $re_data['trade_state'] = 'PAYERROR';
                    return $this->return_data($re_data);
                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $exception) {
            Log::info('收钱啦-查询订单error');
            Log::info($exception->getMessage(). '|' .$exception->getFile(). '|' .$exception->getLine());
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage(). '|' .$exception->getLine()
            ];
            return $this->return_data($err);
        }
    }


    /**
     * 退款
     *
     * 同一笔单的部分退款需要设置相同的订单号和不同的 out_refund_no 。总退款金额不能超过用户实际支付金额(现金券金额不能退款)
     *
     * 商户在退款操作时应该注意退款限制，避免发起不会成功的退款请求，下面是主要的退款限制：
     * 1. 在退款累计金额不超过交易订单支付总额情况下，一笔交易单可以多次退款。退款申请单号由商户生成，所以商户一定要保证退款申请单的唯一性。
     * 2. 目前大多数银行都支持全额退款和部分退款，但是也有少数银行不支持全额退款或部分退款，或者不支持退款。在这种情况下，商户可以与买家协调，线下直接退给买家。
     * 3. 当天同一门店下某支付通道总退款金额不能超出该门店下该支付通道总收入金额，例：门店今日支付宝通道收入金额为0，无法完成退款操作
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function refund($data)
    {
        try {
//            Log::info('收钱啦-退款-入参：');
//            Log::info($data);

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = isset($data['device_id']) ? $data['device_id']: ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //否,String(32),商户订单号
            $transaction_id = $data['transaction_id'] ?? ''; //否,String(32),平台订单号,out_trade_no和transaction_id至少一个必填，同时存在时transaction_id优先
            $out_refund_no = $data['out_refund_no'] ?? ''; //String(32),商户退款单号,32个字符内、可包含字母,确保在商户系统唯一
            $total_fee = $data['total_fee'] ?? ''; //int,订单总金额，单位为分
            $refund_fee = $data['refund_fee'] ?? ''; //int,退款总金额,单位为分,可以做部分退款
            $op_user_id = $data['op_user_id'] ?? ''; //String(32),操作员帐号,默认为商户号

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
            }

            //如果订单号为空或者不存在
            if (!$order) {
                Log::info('收钱啦-查询订单-无果：');
                Log::info($out_trade_no);
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }
            else {
                //判断有没有退款全部完成
                if ($order->refund_amount == $order->total_amount) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '此订单号已经全部退款';
                    return $this->return_data($re_data);
                }
            }

            $OutRefundNo = $out_refund_no; //
            $out_transaction_id = $order->trade_no;
            $out_trade_no = $order->out_trade_no;
            $refundFee_fen = $refund_fee; //退款金额单位 /分

            $already_refund_amount = ($order->refund_amount * 100); //已退款金额,分
            if (($refundFee_fen + $already_refund_amount) > ($order->total_amount * 100)) {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '退款金额大于总金额';
                return $this->return_data($re_data);
            }

            $refundFee_yuan = number_format($refundFee_fen / 100, 2, '.', '');
            $refund_amount = $refundFee_yuan;

            $total_amount = $order->total_amount; //交易总额
            $rate = $order->rate; //订单但是费率
            $new_refund_amount = $order->refund_amount + $refund_amount; //总退款
            $new_fee_amount = ($total_amount - $new_refund_amount) * ($rate/100); //退款后的手续费

            //暂时只支持退全款
//            if ($refundFee_yuan != $order->total_amount) {
//                $re_data['result_code'] = 'FALL';
//                $re_data['result_msg'] = '只支持退全额';
//                return $this->return_data($re_data);
//            }

            $time_end = '';
            $re_data = [
                'version' => '1.0.0',
                'charset' => 'UTF-8',
                'sign_type' => 'MD5',
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
                'return_msg' => '', //否,String(128),返回信息如非空为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //业务结果,SUCCESS/FAIL
                'nonce_str' => $this->nonceStr(), //String(32),随机字符串
                'err_code' => '', //否,String(32),错误代码
                'err_code_des' => '', //否,String(128),错误代码描述
            ];

            $type = $order->ways_type;
            $store_obj = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id', 'pid')
                ->first();
            $config_id = $store_obj->config_id;
            $store_pid = $store_obj->pid;

            //支付宝官方
            if (999 < $type && $type < 1999) {
                $isvconfig = new AlipayIsvConfigController();
                $config_type = '01';
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);

                $storeInfo = $isvconfig->alipay_auth_info($store_id, $store_pid); //获取token

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = "alipay.trade.refund";

                $requests = new AlipayTradeRefundRequest();
                $data_req_ali = "{" .
                    "\"out_trade_no\":\"" . $order->out_trade_no . "\"," .
                    "\"refund_amount\":\"" . $refund_amount . "\"," .
                    "\"out_request_no\":\"" . $OutRefundNo . "\"," .
                    "\"refund_reason\":\"正常退款\"" .
                    "}";
                $requests->setBizContent($data_req_ali);
                $result = $aop->execute($requests, null, $storeInfo->app_auth_token);
                $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;

                //退款成功
                if (!empty($resultCode) && $resultCode == 10000) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $result->$responseNode->sub_msg;
                }
            }

            //直付通
            if (16000 < $type && $type < 16999) {
                $config_type = '03';
                //配置
                $isvconfig = new AlipayIsvConfigController();
                $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = "alipay.trade.refund";

                $requests = new AlipayTradeRefundRequest();
                $data_re = array(
                    'out_trade_no' => $out_trade_no,
                    'refund_amount' => $refund_amount,
                    'out_request_no' => $OutRefundNo,
                    'refund_reason' => '正常退款'
                );

                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'settle_orders_' . $day;
                if (Schema::hasTable($table)) {
                    $settle_orders = DB::table($table)->where('out_trade_no', $out_trade_no)
                        ->where('store_id', $store_id)
                        ->first();
                    if ($settle_orders && $settle_orders->order_settle_amount > 0) {
                        $data_re['refund_royalty_parameters'] = array(
                            0 => array(
                                'trans_out' => $settle_orders->trans_out,
                                'amount' => $settle_orders->order_settle_amount,
                                'desc' => '退款分账'
                            )
                        );
                    }
                }

                $data_re = json_encode($data_re);
                $requests->setBizContent($data_re);
                $result = $aop->execute($requests, null, '');
                $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;

                //退款成功
                if (!empty($resultCode) && $resultCode == 10000) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $result->$responseNode->sub_msg;
                }
            }

            //微信官方扫码退款
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;

                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], // XXX: 绝对路径！！！！
                    'key_path' => $options['payment']['key_path'],     // XXX: 绝对路径！！！！
                    'sub_mch_id' => $wx_sub_merchant_id
                ];

                $payment = Factory::payment($config);
                // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
                $refund = $payment->refund->byOutTradeNumber($order->out_trade_no, $OutRefundNo, $order->total_amount * 100, $refund_amount * 100);
                //Log::info('收钱啦-微信官方扫码退款');
                //Log::info($refund);
                if ($refund['return_code'] == "SUCCESS") {
                    //退款成功
                    if ($refund['result_code'] == "SUCCESS") {
                        $insert_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => 6,
                            'status' => 6,
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $OutRefundNo, //退款单号
                            'store_id' => $store_id,
                            'merchant_id' => (int)$merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo, //平台退款单号
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                        $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } else {
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $refund['result_msg'];
                    }
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $refund['return_msg'];
                }
            }

            //京东收银支付退款
            if (5999 < $type && $type < 6999) {
                //读取配置
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] =$refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联拓富收银支付退款
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();
                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] = $refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $out_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //其他情况
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //快钱收银支付退款
            if (2999 < $type && $type < 3999) {
                //读取配置
                $config = new MyBankConfigController();
                $mybank_merchant = $config->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $wx_AppId = $mybank_merchant->wx_AppId;
                $MyBankConfig = $config->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $obj = new TradePayController();
                $MerchantId = $mybank_merchant->MerchantId;
                $RefundAmount =$refund_amount;
                $return = $obj->mybankrefund($MerchantId, $order->out_trade_no, $OutRefundNo, $RefundAmount, $config_id);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    //其他情况
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //和融通收银支付退款
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['trade_no'] = $order->trade_no;
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['notifyUrl'] = url('/api/jd/refund_url'); //通知地址;
                $data['mid'] = $h_merchant->h_mid;
                $data['md_key'] = $h_config->md_key; //
                $data['orgNo'] = $h_merchant->orgNo; //
                $data['outRefundNo'] = $OutRefundNo;
                $data['amount'] = $refund_amount;
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付支付退款
            if (12999 < $type && $type < 13999) {
                //读取配置
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付配置不存在请检查配置'
                    ]);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $data['refund_amount'] = $refund_amount;
//                Log::info('随行付-收钱啦-退款-入参');
//                Log::info($data);
                $return = $obj->refund($data);
//                Log::info('随行付-收钱啦-退款');
//                Log::info($return);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' =>$refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                }
                elseif(($return['status'] == 0) && ($return['data']['code'] == '0000')){
                    //TODO: 退款状态未知，先让收钱啦显示成功
//                    Log::info('随行付退款状态未知，先让收钱啦显示成功');
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败 其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付a支付退款
            if (18999 < $type && $type < 19999) {
                //读取配置
                $config = new VbillConfigController();
                $vbill_config = $config->vbilla_config($config_id);
                if (!$vbill_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付A配置不存在请检查配置'
                    ]);
                }

                $vbill_merchant = $config->vbilla_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '随行付A商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $data['refund_amount'] = $refund_amount;
//                Log::info('随行付A-收钱啦-退款-入参');
//                Log::info($data);
                $return = $obj->refund($data);
//                Log::info('随行付A-收钱啦-退款');
//                Log::info($return);

                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' =>$refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                }
                elseif(($return['status'] == 0) && ($return['data']['code'] == '0000')){
                    //TODO: 退款状态未知，先让收钱啦显示成功
//                    Log::info('随行付A退款状态未知，先让收钱啦显示成功');
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //传化收银支付退款
            if (11999 < $type && $type < 12999) {
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $OutRefundNo = time();
                $data = [];
                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $data['refund_trade_no'] = $OutRefundNo; //
                $data['refund_fee'] = $refund_amount; //
                $return = $obj->refund($data);
                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //新大陆
            if (7999 < $type && $type < 8999) {
                $config = new NewLandConfigController();
                $new_land_config = $config->new_land_config($config_id);
                if (!$new_land_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '新大陆通道配置不存在';
                    return $this->return_data($re_data);
                }

                $new_land_merchant = $config->new_land_merchant($store_id, $store_pid);
                if (!$new_land_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '商户新大陆通道未开通';
                    return $this->return_data($re_data);
                }
                $request_data = [
                    'out_trade_no' => $out_trade_no,
                    'trade_no' => $order->trade_no,
                    'key' => $new_land_merchant->nl_key,
                    'org_no' => $new_land_config->org_no,
                    'merc_id' => $new_land_merchant->nl_mercId,
                    'trm_no' => $new_land_merchant->trmNo,
                    'op_sys' => '3',
                    'opr_id' => $store_obj->merchant_id,
                    'trm_typ' => 'T',
                    'txnAmt'=>$refund_amount*100,
                ];
                $obj = new PayController();
                $return = $obj->refund($request_data);

                //退款请求成功
                if ($return["status"] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
                    //退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //哆啦宝
            if (14999 < $type && $type < 15999) {
                $OutRefundNo = "dlbscan" . date('YmdHis') . str_pad(rand(0, 9999), 4, 0);
                $manager = new ManageController();
                $dlb_config = $manager->pay_config($config_id);
                if (!$dlb_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '哆啦宝配置配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $dlb_merchant = $manager->dlb_merchant($store_id, $store_pid);
                if (!$dlb_merchant && !empty($dlb_merchant->mch_num) && !empty($dlb_merchant->shop_num)) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = '哆啦宝配置商户未补充商户编号等信息';
                    return $this->return_data($re_data);
                }

                $refund_data = [
                    "accessKey" => $dlb_config->access_key,
                    "secretKey" => $dlb_config->secret_key,
                    "agentNum" => $dlb_config->agent_num,
                    "customerNum" => $dlb_merchant->mch_num,
                    "shopNum" => $dlb_merchant->shop_num,
                    "requestNum" => $out_trade_no,
                    "refundRequestNum" => $OutRefundNo,
                    'refundPartAmount'=>$refund_amount
                ];
                $return = $manager->pay_refund($refund_data);
                if ($return['status'] == 1) {
                    //退款请求成功
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //汇付-收银通道 退款
            if (17999 < $type && $type < 18999) {
                $config = new HuiPayConfigController();
                $hui_pay_config = $config->hui_pay_config($config_id);
                if (!$hui_pay_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '汇付配置不存在请检查配置'
                    ]);
                }

                $hui_pay_merchant = $config->hui_pay_merchant($store_id, $store_pid);
                if (!$hui_pay_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '汇付商户不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\HuiPay\PayController();
                $data['notify_url'] = url('/api/huipay/return_pay_notify_url'); //回调地址
                $data['request_url'] = $obj->user_refund; //请求地址
                $data['mer_cust_id'] = $hui_pay_config->mer_cust_id; //商户客户号
                $data['user_cust_id'] = $hui_pay_merchant->user_cust_id; //用户客户号
                $data['private_key'] = $hui_pay_config->private_key;
                $data['public_key'] = $hui_pay_config->public_key;
                $data['org_id'] = $hui_pay_config->org_id;
                $data['out_trade_no'] = $order->out_trade_no; //订单号
                $data['refund_amount'] = $refundFee_yuan; //退款金额
                $data['device_id'] = $hui_pay_merchant->device_id??''; //机具id
                $data['trade_no'] = $order->trade_no; //支付订单号
                $return = $obj->refund($data); //0-系统错误 1-成功 2-退款中 3-失败
//                Log::info('收钱啦-汇付-退款');
//                Log::info(str_replace("\\/", "/", json_encode($return, JSON_UNESCAPED_UNICODE)));
                //退款请求成功
                if ($return["status"] == '1') {
                    if (isset($return['data']) && !empty($return['data'])) {
                        $return_data = $return['data'];
                    }
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no); //更新订单状态

                    //退款成后更新退款表
                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //工行 退款
            if (19999 < $type && $type < 20999) {
                $config = new LianfuConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfu\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['refund_no'] = time(); //
                $data['pay_amount'] = $refund_amount; //
                $return = $obj->refund($data);
                if ($return['status'] == 1) {
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //海科融通 退款
            if (21999 < $type && $type < 22999) {
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通配置不存在请检查配置'
                    ]);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '海科融通商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_return_data = [
                    'access_id' => $hkrt_config->access_id,
                    'refund_amount' => $refund_amount, //退款金额,(银联二维码只能全额退款)退款金额，以元为单位
                    'trade_no' => $order->trade_no, //SaaS平台的交易订单编号
                    'out_trade_no' => $order->out_trade_no,
                    'notify_url' => url('/api/hkrt/refund_notify_url'), //回调地址
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('海科融通-收钱啦-退款');
//                Log::info($hkrt_return_data);
                $return = $obj->refund($hkrt_return_data); //0-系统错误 1-成功 2-失败 3-结果未知
//                Log::info($return);

                //退款成功
                if ($return['status'] == 1) {
                    $hkrt_refund_no = $return['data']['refund_no']; //SaaS平台的退款订单编号
                    $refund_amount = $return['data']['refunded_amount']; //已退款金额
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 6,
                        'status' => 6,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $hkrt_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$hkrt_refund_no, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == '2'){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //未知
                elseif($return['status'] == '3') {
                    //TODO: 退款状态未知，先让收钱啦显示成功
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //其他情况
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //易生支付 退款
//            if (20999 < $type && $type < 21999) {
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                    //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }
                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付配置不存在请检查配置'
                    ]);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '易生支付商户号不存在'
                    ]);
                }

                //当天的交易只能全额撤销,日切时间为渠道服务器的00:00；非当日才可退款
                $obj = new \App\Api\Controllers\Easypay\PayController();
                $now_time_start = strtotime(date('Y-m-d 00:00:00', time()));
                $now_time_end = strtotime(date('Y-m-d 23:59:59', time()));
                $order_pay_time = strtotime($order->pay_time);

                if (($order_pay_time > $now_time_start) && ($order_pay_time <= $now_time_end)) {
                    $easypay_revoke_data = [
                        'channel_id' => $easypay_config->channel_id, //渠道编号
                        'mno' => $easypay_merchant->termMercode, //终端商戶编号
                        'device_id' => $easypay_merchant->termTermcode, //终端编号
                        'out_trade_no' => $out_trade_no, //订单号
                        'trade_no' => $order->trade_no //系统订单号
                    ];
//                    Log::info('收钱啦易生支付-当日交易撤销');
//                    Log::info($easypay_revoke_data);
                    $return = $obj->order_close($easypay_revoke_data); //-1 系统错误 0-其他 1-成功
//                    Log::info($return);

                    //成功
                    if ($return['status'] == '1') {
                        $easypay_refund_no = $return['data']['oriwtorderid']; //撤销的商户订单号
                        $refund_amount = isset($return['data']['clearamt'])? ($return['data']['clearamt'] / 100) : $order->total_amount; //结算金额，单位分
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $easypay_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
//退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$easypay_refund_no, //平台退款单号
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $easypay_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $easypay_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } //其他情况 退款失败
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL'; //
                        $re_data['return_msg'] = $message;
                    }
                } else {
                    $easypay_return_data = [
                        'channel_id' => $easypay_config->channel_id, //渠道编号
                        'mer_id' => $easypay_merchant->termMercode, //终端商戶编号
                        'term_id' => $easypay_merchant->termTermcode, //终端编号
                        'out_trade_no' => $order->out_trade_no, //商户订单号
                        'trade_no' => $order->trade_no, //原交易的系统订单号
                        'refund_amount' => $refund_amount, //退款金额,以元为单位
                    ];
//                    Log::info('易生支付-收钱啦-退款');
//                    Log::info($easypay_return_data);
                    $return = $obj->refund($easypay_return_data); //-1 系统错误 0-其他 1-成功 2-失败
//                    Log::info($return);

                    $easypay_refund_no = $return['data']['oriwtorderid']; //易生退货单号

                    //退款成功
                    if ($return['status'] == '1') {
                        $refund_amount = $order->total_amount; //已退款金额
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $easypay_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
//退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$easypay_refund_no, //平台退款单号
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $easypay_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $easypay_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    } //退款失败
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $message;
                    }
                }
            }

            //邮政 退款
            if (26000 < $type && $type < 26999) {
                $config = new LianfuyoupayConfigController();
                $h_merchant = $config->lianfu_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户号不存在'
                    ]);
                }

                $obj = new \App\Api\Controllers\lianfuyouzheng\PayController();
                $data['apikey'] = $h_merchant->apikey; //
                $data['signkey'] = $h_merchant->signkey; //
                $data['pos_sn'] = $h_merchant->pos_sn; //
                $data['out_trade_no'] = $out_trade_no; //
                $data['refund_no'] = time(); //
                $data['pay_amount'] = $refund_amount; //
                $data['goods_name'] = '商品'; //

                $return = $obj->refund($data);

                if ($return['status'] == 1) {
                    //退款请求成功
                    $insert_data = [
                        'status' => 6,
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => 3,
                        'status' => 3,
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount, //退款金额
                        'refund_no' => $OutRefundNo, //退款单号
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$OutRefundNo, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                    $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //葫芦天下
            if (22999 < $type && $type < 23999) {
                $manager = new \App\Api\Controllers\Hltx\ManageController();

                $hltx_merchant = $manager->pay_merchant($store_id, $store_pid);
                $qd = $hltx_merchant->qd;
                $hltx_config = $manager->pay_config($config_id, $qd);
                if (!$hltx_config) {
                    return json_encode([
                        'status' => 2,
                        'message' => 'HL支付配置不存在请检查配置'
                    ]);
                }

                $manager->init($hltx_config);
                switch ($type) {
                    case 23001:
                        $pay_channel = 'ALI';
                        break;
                    case 23002:
                        $pay_channel = 'WX';
                        break;
                    case 23004:
                        $pay_channel = 'UPAY';
                        break;
                    default:
                        $pay_channel = 'ALI';
                        break;
                }

                if (!$hltx_merchant || empty($hltx_merchant->mer_no)) {
                    return json_encode([
                        'status' => 2,
                        'message' => '商户未成功开通HL通道!'
                    ]);
                }

                $OutRefundNo = "hltx" . date('YmdHis') . str_pad(rand(0, 9999), 4, 0);
                $hltx_data = [
                    'merNo' => $hltx_merchant->mer_no,
                    'amount' => $refund_amount * 100,
                    'orderNo' => $OutRefundNo,
                    'oriOrderNo' => $out_trade_no,
                    'orderInfo' => '用户退款',
                    'deviceIp' => \EasyWeChat\Kernel\Support\get_client_ip()
                ];
                $return = $manager->refund_order($hltx_data);
                if ($return['status'] == 1) {
                    $return = $return['data'];
                    if ($return['tradeStatus'] == 'S' || $return['tradeStatus'] == 'R') {
                        //退款请求成功
                        $insert_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => 3,
                            'status' => 3,
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $OutRefundNo, //退款单号
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
//退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$OutRefundNo, //平台退款单号
                        ]);
                        $re_data['result_code'] = 'SUCCESS';
                        $re_data['result_msg'] = '退款成功';
                        $re_data['refundNo'] = $OutRefundNo;
                        $re_data['refundFee'] = $refund_amount * 100;

                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $OutRefundNo; //String(32),商户退款单号
                        $re_data['refund_id'] = $OutRefundNo; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    }
                    /*elseif($return['tradeStatus']=='R'){
                        $message = '等待退款';
                        //退款失败
                        $re_data['result_code'] = 'USERPAYING';
                        $re_data['result_msg'] = $message;
                        $re_data['refundNo'] = $OutRefundNo;
                        $re_data['refundFee'] = intval($refund_amount * 100).'';
                        $number=5;
                        for($i=0;$i<$number;$i++){
                            sleep(1);
                            \App\Common\Log::write('退款中查询','refund.log');
                            $hltx_data=[
                                'merNo'=>$hltx_merchant->mer_no,
                                'orderNo'=>$OutRefundNo,
                            ];
                            $query_result=$manager->query_order($hltx_data);
                            \App\Common\Log::write($query_result,'refund.log');
                            if($query_result['status']==1){
                                $query_result=$query_result['data'];
                                if($query_result['tradeStatus']=='R'){
                                    if($query_result['subTradeStatus']=='REFUNDING'){
                                        continue;
                                    }elseif($query_result['subTradeStatus']=='FAILED'||$query_result['subTradeStatus']=='SYS_FAILED'){
                                        $message = '退款失败';
                                        //退款失败
                                        $re_data['result_code'] = 'FALL';
                                        $re_data['result_msg'] = $message;
                                        break;
                                    }elseif($query_result['subTradeStatus']=='COMPLETE'){
                                        $insert_data = [
                                            'status' => 6,
                                            'pay_status' => 6,
                                            'pay_status_desc' => '已退款',
                                            'fee_amount' => 0,
                                            'refund_amount' => $refund_amount
                                        ];
                                        $this->update_day_order($insert_data, $out_trade_no);

                                        RefundOrder::create([
                                            'pay_status' => 3,
                                            'status' => 3,
                                            'type' => $type,
                                            'ways_source' => $order->ways_source,
                                            'status_desc' => '退款',
                                            'refund_amount' => $refund_amount, //退款金额
                                            'refund_no' => $OutRefundNo, //退款单号
                                            'store_id' => $store_id,
                                            'merchant_id' => $store->merchant_id,
                                            'out_trade_no' => $order->out_trade_no,
                                            'trade_no' => $order->trade_no
                                        ]);

                                        $re_data['result_code'] = 'SUCCESS';
                                        $re_data['result_msg'] = '退款成功';
                                        $re_data['refundNo'] = $OutRefundNo;
                                        $re_data['refundFee'] = $refund_amount * 100;
                                        break;
                                    }
                                }elseif($query_result['tradeStatus']=='S'){
                                    if($query_result['subTradeStatus']=='COMPLETE'){
                                        $insert_data = [
                                            'status' => 6,
                                            'pay_status' => 6,
                                            'pay_status_desc' => '已退款',
                                            'fee_amount' => 0,
                                            'refund_amount' => $refund_amount
                                        ];
                                        $this->update_day_order($insert_data, $out_trade_no);

                                        RefundOrder::create([
                                            'pay_status' => 3,
                                            'status' => 3,
                                            'type' => $type,
                                            'ways_source' => $order->ways_source,
                                            'status_desc' => '退款',
                                            'refund_amount' => $refund_amount, //退款金额
                                            'refund_no' => $OutRefundNo, //退款单号
                                            'store_id' => $store_id,
                                            'merchant_id' => $store->merchant_id,
                                            'out_trade_no' => $order->out_trade_no,
                                            'trade_no' => $order->trade_no
                                        ]);

                                        $re_data['result_code'] = 'SUCCESS';
                                        $re_data['result_msg'] = '退款成功';
                                        $re_data['refundNo'] = $OutRefundNo;
                                        $re_data['refundFee'] = $refund_amount * 100;
                                        break;
                                    }
                                }else{
                                    break;
                                }
                            }else{
                                break;
                            }
                        }
                    }*/
                    else {
                        $message = '退款失败';
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $message;
                    }
                } else {
                    $message = $return['message'];
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联动优势 退款
            if (4999 < $type && $type < 5999) {
                $config = new LinkageConfigController();
                $linkage_config = $config->linkage_config($config_id);
                if (!$linkage_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '联动优势支付配置不存在，请检查配置'
                    ]);
                }

                $linkage_merchant = $config->linkage_merchant($store_id, $store_pid);
                if (!$linkage_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '联动优势商户号不存在'
                    ]);
                }

                //针对交易当天的成功订单可以进行撤销，过了账期则需要走退费接口。仅支持微信支付宝刷卡交易（即用户被扫）的撤销，其他支付成功订单如需实现相同功能请调用3.5退款请求接口
                $obj = new \App\Api\Controllers\Linkage\PayController();
                $now_time_start = strtotime(date('Y-m-d 00:00:00', time()));
                $now_time_end = strtotime(date('Y-m-d 23:59:59', time()));
                $order_pay_time = strtotime($order->pay_time);

                if (($order_pay_time > $now_time_start) && ($order_pay_time <= $now_time_end)) {
                    $linkage_revoke_data = [
                        'acqSpId' => $linkage_config->mch_id, //
                        'acqMerId' => $linkage_merchant->acqMerId, //
                        'out_trade_no' => $out_trade_no, //
                        'privateKey' => $linkage_config->privateKey, //
                        'publicKey' => $linkage_config->publicKey //
                    ];
//                    Log::info('收钱啦-联动优势-当日交易撤销');
//                    Log::info($linkage_revoke_data);
                    $return = $obj->order_revoke($linkage_revoke_data); //-1系统错误；0-其他；1-处理成功；2-验签失败
//                    Log::info($return);
                    //成功
                    if ($return['status'] == '1') {
                        $linkage_refund_no = $return['data']['transactionId']; //联动流水号
                        $refund_amount = $order->total_amount;
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $linkage_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
//退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$linkage_refund_no, //平台退款单号
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $linkage_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $linkage_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    }
                    else {
                        //其他情况
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL'; //退款失败
                        $re_data['return_msg'] = $message;
                    }
                }
                else { //退款
                    $linkage_return_data = [
                        'acqSpId' => $linkage_config->mch_id, //
                        'acqMerId' => $linkage_merchant->acqMerId, //
                        'out_trade_no' => $out_trade_no, //
                        'total_amount' => $order->total_amount, //
                        'refund_amount' => $refund_amount, //
                        'privateKey' => $linkage_config->privateKey,
                        'publicKey' => $linkage_config->publicKey
                    ];
//                    Log::info('联动优势-收钱啦-退款');
//                    Log::info($linkage_return_data);
                    $return = $obj->refund($linkage_return_data); //（支持部分退款，支持对90天以内的成功订单） -1系统错误；0-其他；1-成功；2-验签失败；3-失败
//                    Log::info($return);

                    $linkage_refund_no = $return['data']['transactionId']; //联动退款流水号

                    //退款成功
                    if ($return['status'] == '1') {
                        $refund_amount = $order->total_amount; //已退款金额
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $new_refund_amount,
                            'fee_amount' => $new_fee_amount
                        ];
                        $this->update_day_order($insert_data, $out_trade_no);

                        RefundOrder::create([
                            'pay_status' => '6',
                            'status' => '6',
                            'type' => $type,
                            'ways_source' => $order->ways_source,
                            'status_desc' => '退款',
                            'refund_amount' => $refund_amount,
                            'refund_no' => $linkage_refund_no,
                            'store_id' => $store_id,
                            'merchant_id' => $merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->trade_no
                        ]);
//退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$linkage_refund_no, //平台退款单号
                        ]);
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['out_refund_no'] = $linkage_refund_no; //String(32),商户退款单号
                        $re_data['refund_id'] = $linkage_refund_no; //String(32),平台退款单号
                        $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                        $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                        $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                    }
                    //失败
                    elseif($return['status'] == '3'){
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = '退款失败';
                    } //其他
                    else {
                        $message = $return['message'];
                        $re_data['result_code'] = 'FALL'; //退款失败
                        $re_data['return_msg'] = $message;
                    }
                }
            }

            //威富通 退款
            if (26999 < $type && $type < 27999) {
                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $config = new WftPayConfigController();
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付配置不存在，请检查配置'
                    ]);
                }

                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '威富通支付商户号不存在'
                    ]);
                }

                $wftpay_return_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $out_trade_no,
                    'total_amount' => $order->total_amount,
                    'refund_fee' => $refund_amount,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通-收钱啦-退款-入参');
//                Log::info($wftpay_return_data);
                $obj = new WftPayPayController();
                $return = $obj->refund($wftpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('威富通-收钱啦-退款');
//                Log::info($return);

                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $wftpay_refund_no = isset($return['data']['out_refund_id_'.$refund_count]) ?$return['data']['out_refund_id_'.$refund_count]: $return['data']['refund_id_'.$refund_count]; //第三方退款单号
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $wftpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$wftpay_refund_no, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $wftpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //退款失败
                    $re_data['return_msg'] = $message;
                }
            }

            //汇旺财 退款
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付配置不存在，请检查配置'
                    ]);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    return json_encode([
                        'status' => '2',
                        'message' => '汇旺财支付商户号不存在'
                    ]);
                }

                $hwcpay_return_data = [
                    'mch_id' => $hwcpay_merchant->mch_id, //门店号
                    'merchant_num' => $hwcpay_merchant->merchant_num, //商户号
                    'out_trade_no' => $out_trade_no,
                    'total_amount' => $order->total_amount,
                    'refund_fee' => $refund_amount,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财-收钱啦-退款-入参');
//                Log::info($hwcpay_return_data);
                $obj = new HwcPayPayController();
                $return = $obj->refund($hwcpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('汇旺财-收钱啦-退款');
//                Log::info($return);
                //退款成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $hwcpay_refund_no = isset($return['data']['out_refund_id_'.$refund_count])? $return['data']['out_refund_id_'.$refund_count]: $return['data']['refund_id_'.$refund_count]; //第三方退款单号
                    $refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //已退款金额
                    $insert_data = [
                        'status' => '6',
                        'pay_status' => 6,
                        'pay_status_desc' => '已退款',
                        'refund_amount' => $new_refund_amount,
                        'fee_amount' => $new_fee_amount
                    ];
                    $this->update_day_order($insert_data, $out_trade_no);

                    RefundOrder::create([
                        'pay_status' => '6',
                        'status' => '6',
                        'type' => $type,
                        'ways_source' => $order->ways_source,
                        'status_desc' => '退款',
                        'refund_amount' => $refund_amount,
                        'refund_no' => $hwcpay_refund_no,
                        'store_id' => $store_id,
                        'merchant_id' => $merchant_id,
                        'out_trade_no' => $order->out_trade_no,
                        'trade_no' => $order->trade_no
                    ]);
//退款成功后的操作
                    RefundSuccessAction::action([
                        'out_trade_no'=>$out_trade_no,
                        'refund_no' =>$hwcpay_refund_no, //平台退款单号
                    ]);
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台订单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['out_refund_no'] = $hwcpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id'] = $hwcpay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel'] = 'ORIGINAL'; //String(32),退款渠道,默认:原路退款
                    $re_data['total_fee'] =  $total_fee ?? $order->total_amount*100; //int,总金额，以分为单位
                    $re_data['refund_fee'] = $refund_fee ?? $order->total_amount*100; //int,退款总金额,单位为分
                } //失败
                elseif($return['status'] == 2){
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                } //其他 退款失败
                else {
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL'; //
                    $re_data['return_msg'] = $message;
                }
            }

            return $this->return_data($re_data);
        } catch (\Exception $ex) {
            Log::info('收钱啦-退款error');
            Log::info($ex->getMessage() .' | '.$ex->getFile().' | '. $ex->getLine());
            $re_data = [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage() .' | '. $ex->getLine()
            ];
            return $this->return_data($re_data);
        }
    }


    /**
     * 退款查询
     *
     * 提交退款申请后，通过调用该接口查询退款状态。退款有一定延时，用零钱支付的退款20分钟内到账， 银行卡支付的退款3个工作日后重新查询退款状态
     * @param $data
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function refund_query($data)
    {
        try {
            Log::info('收钱啦-退款查询-入参');
            Log::info($data);

            //公共参数
            $version = $data['version'] ?? '1.0.0'; //接口版本1.0.0
            $method = $data['method'] ?? ''; //处理方式(根据请求的接口决定),pay.weixin.jsapi
            $charset = $data['charset'] ?? 'UTF-8'; //否,字符集,可选值，默认为UTF-8
            $sign_type = $data['sign_type'] ?? 'MD5'; //否,签名方式,签名类型，取值：MD5，默认：MD5
            $sign = $data['sign'] ?? ''; //签名,MD5签名结果
            $appid = $data['appid'] ?? ''; //应用ID,收钱啦聚合支付分配的应用ID
            $nonce_str = $data['nonce_str'] ?? ''; //随机字符串，不长于32位
            $device_id = $data['device_id'] ?? ''; //否,设备ID,ERP/POS厂商接入,门店二维码ID或自定义设备编号
            $mch_id = isset($data['mch_id']) ? $data['mch_id']: ''; //否,商户,商户ID,商户编号

            //业务参数
            $out_trade_no = $data['out_trade_no'] ?? ''; //否,String(32),商户订单号
            $transaction_id = $data['transaction_id'] ?? ''; //否,String(32),平台交易号
            $out_refund_no = $data['out_refund_no'] ?? ''; //否,String(32),商户退款单号,32个字符内、可包含字母,确保在商户系统唯一
            $refund_id = $data['refund_id'] ?? ''; //否,String(32),平台退款单号(refund_id、out_refund_no、out_trade_no、transaction_id四个参数必填一个，如果同时存在优先级为：refund_id>out_refund_no>transaction_id>out_trade_no)

            $winCodeStoreObj = WincodeStore::where('device_id', $device_id)->first();
            if (!$winCodeStoreObj) {
                return $this->return_data([
                    'return_code' => 'FAIL',
                    'return_msg' => '设备尚未绑定门店'
                ]);
            }

            $store_id = $winCodeStoreObj->store_id;
            $merchant_id = $winCodeStoreObj->merchant_id;
            $merchant_name = $winCodeStoreObj->merchant_name;

            //调用系统前参数
            $order = '';
            if (!empty($out_trade_no)) {
                $order = Order::where('store_id', $store_id)
                    ->where('qwx_no', '=', $out_trade_no)
                    ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                    ->first();
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
                if (!$order) {
                    $order = Order::where('store_id', $store_id)
                        ->where('out_trade_no', '=', $out_trade_no)
                        ->select('id', 'ways_source', 'company', 'ways_type', 'ways_type_desc', 'pay_status', 'out_trade_no', 'trade_no', 'total_amount', 'qwx_no', 'rate', 'merchant_id', 'store_id', 'user_id', 'store_name', 'fee_amount')
                        ->first();
                }
            }

            //如果订单号为空或者不存在
            if (!$order) {
                Log::info('收钱啦-查询订单-无果：');
                Log::info($out_trade_no);
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '订单号不存在';
                return $this->return_data($re_data);
            }

            //上线后去掉开始
            $refund = RefundOrder::where('out_trade_no', $order->out_trade_no)
                ->select('refund_no')
                ->first();

            //如果订单号为空或者不存在
            if (!$refund) {
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = '退款订单号不存在';
                return $this->return_data($re_data);
            }
            $refundNo = $refund->refund_no;
            //上线后去掉结束

            $channel = '';
            if ($order->ways_type == 1001) {
                $channel = 'ali_barcode_pay';
            }

            if ($order->ways_type == 2001) {
                $channel = "wx_barcode_pay";
            }

            $re_data = [
                'version' => '1.0.0', //版本号
                'charset' => 'UTF-8', //字符集
                'sign_type' => 'MD5', //签名类型，取值：MD5
                'return_code' => 'SUCCESS', //SUCCESS/FALL 此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断
                'return_msg' => '', //否,String(128),返回信息，如非空，为错误原因
                'device_info' => $device_id, //
                'result_code' => 'SUCCESS', //String(8),业务结果 SUCCESS/FAIL
                'nonce_str' => $this->nonceStr() //String(32),随机字符串
            ];

            $type = $order->ways_type;
            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'merchant_id')
                ->first();
            $config_id = $store->config_id;
            $store_pid = $store->pid;
            $out_trade_no = $order->out_trade_no;

            //官方支付宝查询
            if (999 < $type && $type < 1999) {
                $config = AlipayIsvConfig::where('config_id', $config_id)
                    ->where('config_type', '01')
                    ->first();

                //获取token
                $storeInfo = AlipayAppOauthUsers::where('store_id', $data['merchantId'])
                    ->select('app_auth_token')
                    ->first();

                $aop = new AopClient();
                $aop->apiVersion = "2.0";
                $aop->appId = $config->app_id;
                $aop->rsaPrivateKey = $config->rsa_private_key;
                $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
                $aop->signType = "RSA2"; //升级算法
                $aop->gatewayUrl = $config->alipay_gateway;
                $aop->format = "json";
                $aop->charset = "GBK";
                $aop->version = "2.0";
                $aop->method = 'alipay.trade.fastpay.refund.query';
                $requests = new AlipayTradeFastpayRefundQueryRequest();
                $requests->setBizContent("{" .
                    "    \"out_trade_no\":\"" . $order->out_trade_no . "\"," .
                    "    \"out_request_no\":\"" . $refundNo . "\"" .
                    "  }");
                $refund = $aop->execute($requests, '', $storeInfo->app_auth_token);

                //支付成功
                if ($refund->alipay_trade_fastpay_refund_query_response->code == 10000) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->out_request_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->out_request_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $refund->alipay_trade_fastpay_refund_query_response->refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $order->updated_at); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $message = $refund->alipay_trade_fastpay_refund_query_response->sub_msg;
                    $re_data['result_code'] = 'FALL';
                    $re_data['result_msg'] = $message;
                }
            }

            //微信官方扫码
            if (1999 < $type && $type < 2999) {
                $config = new WeixinConfigController();
                $options = $config->weixin_config($config_id);
                $weixin_store = $config->weixin_merchant($store_id, $store_pid);
                $wx_sub_merchant_id = $weixin_store->wx_sub_merchant_id;
                $config = [
                    'app_id' => $options['app_id'],
                    'mch_id' => $options['payment']['merchant_id'],
                    'key' => $options['payment']['key'],
                    'cert_path' => $options['payment']['cert_path'], // XXX: 绝对路径！！！！
                    'key_path' => $options['payment']['key_path'],     // XXX: 绝对路径！！！！
                    'sub_mch_id' => $wx_sub_merchant_id,
                    // 'device_info'     => '013467007045764',
                    // 'sub_app_id'      => '',
                    // ...
                ];

                $payment = Factory::payment($config);
                $refund_query = $payment->refund->queryByOutTradeNumber($order->out_trade_no);
                if ($refund_query['return_code'] == "SUCCESS") {
                    //退款成功
                    if ($refund_query['result_code'] == "SUCCESS") {
                        $refund_count = $refund_query['refund_count'];
                        $refund_count_num = $refund_count - 1;
                        $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['refund_count'] = $refund_count; //int,退款记录数
                        $re_data['out_refund_no_'.$refund_count_num] = $refund_query['refund_status_'.$refund_count_num]; //String(32),商户退款单号
                        $re_data['refund_id_'.$refund_count_num] = $refund_query['refund_status_'.$refund_count_num]; //String(32),平台退款单号
                        $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                        $re_data['refund_fee_'.$refund_count_num] = $refund_query['refund_fee']; //int,退款总金额,单位为分,可以做部分退款
                        $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $refund_query['refund_success_time_'.$refund_count_num]); //否,String(14),退款时间,yyyyMMddHHmmss
                    } else {
                        //
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = $refund_query['result_msg'];
                    }
                } else {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $refund_query['return_msg'];
                }
            }

            //京东收银支付退款查询
            if (5999 < $type && $type < 6999) {
                //读取配置
                $config = new JdConfigController();
                $jd_config = $config->jd_config($config_id);
                if (!$jd_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $jd_merchant = $config->jd_merchant($store_id, $store_pid);
                if (!$jd_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Jd\PayController();
                $data = [];
                $data['request_url'] = $obj->refund_query_url; //请求地址;
                $data['merchant_no'] = $jd_merchant->merchant_no;
                $data['md_key'] = $jd_merchant->md_key; //
                $data['des_key'] = $jd_merchant->des_key; //
                $data['systemId'] = $jd_config->systemId; //
                $data['outRefundNo'] = $refundNo;
                $return = $obj->refund_query($data);
                //退款成功
                if ($return["status"] == 1) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['amount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //联拓富收银支付退款查询
            if (9999 < $type && $type < 10999) {
                //读取配置
                $config = new LtfConfigController();

                $ltf_merchant = $config->ltf_merchant($store_id, $store_pid);
                if (!$ltf_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '京东商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Ltf\PayController();
                $data = [];
                $data['request_url'] = $obj->refund_query_url; //请求地址;
                $data['merchant_no'] = $ltf_merchant->merchantCode;
                $data['appId'] = $ltf_merchant->appId; //
                $data['key'] = $ltf_merchant->md_key; //
                $data['outRefundNo'] = $refundNo;
                $return = $obj->refund_query($data);
                //退款成功
                if ($return["status"] == 1) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['refundAmount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['time'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //快钱支付
            if (2999 < $type && $type < 3999) {
                //读取配置
                $config = new MyBankConfigController();
                $mybank_merchant = $config->mybank_merchant($store_id, $store_pid);
                if (!$mybank_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '快钱商户号不存在';
                    return $this->return_data($re_data);
                }

                $wx_AppId = $mybank_merchant->wx_AppId;
                $MyBankConfig = $config->MyBankConfig($config_id, $wx_AppId);
                if (!$MyBankConfig) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '快钱配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $aop = new \App\Api\Controllers\MyBank\BaseController();
                $ao = $aop->aop($config_id);
                $ao->url = $aop->MY_BANK_request2;
                $ao->Function = "ant.mybank.bkmerchanttrade.refundQuery";
                $data = [
                    'MerchantId' => $mybank_merchant->MerchantId,
                    'OutRefundNo' => $refundNo,
                ];
                $re = $ao->Request($data);
                if ($re['status'] == 0) {
                    //退款失败
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $re['msg'];
                    return $this->return_data($re_data);

                }

                $body = $re['data']['document']['response']['body'];
                $Result = $body['RespInfo'];
                //支付成功
                if ($Result['ResultStatus'] == "S") {
                    $GmtRefundment = $body['GmtRefundment'];

                    //退款成功
                    if ($body['TradeStatus'] == "succ") {
                        $refund_count = 1;
                        $refund_count_num = $refund_count - 1;
                        $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                        $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                        $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                        $re_data['refund_count'] = $refund_count; //int,退款记录数
                        $re_data['out_refund_no_'.$refund_count_num] = $body['OutRefundNo']; //String(32),商户退款单号
                        $re_data['refund_id_'.$refund_count_num] = $body['OutRefundNo']; //String(32),平台退款单号
                        $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                        $re_data['refund_fee_'.$refund_count_num] = $body['RefundAmount']; //int,退款总金额,单位为分,可以做部分退款
                        $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $GmtRefundment); //否,String(14),退款时间,yyyyMMddHHmmss
                    }

                    //退款中
                    if ($body['TradeStatus'] == "refunding") {
                        $re_data['result_code'] = 'USERPAYING';
                        $re_data['return_msg'] = '退款中';
                        $re_data['refundNo'] = $refundNo;
                    }

                    //失败
                    if ($body['TradeStatus'] == "fail") {
                        $re_data['result_code'] = 'FALL';
                        $re_data['return_msg'] = '退款失败';
                        $re_data['refundNo'] = $refundNo;
                    }
                } else {
                    //其他情况
                    $message = $Result['ResultMsg'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //和融通
            if (8999 < $type && $type < 9999) {
                //读取配置
                $config = new HConfigController();
                $h_config = $config->h_config($config_id);
                if (!$h_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '和融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $h_merchant = $config->h_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '和融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Huiyuanbao\PayController();
                $data = [];
                $data['out_trade_no'] = $order->out_trade_no;
                $data['request_url'] = $obj->order_query_url; //暂时用查询代替
                $data['mid'] = $h_merchant->h_mid;
                $data['md_key'] = $h_config->md_key; //
                $data['orgNo'] = $h_merchant->orgNo; //
                $return = $obj->order_query($data); //暂时用查询代替
                //退款成功
                if ($return["status"] == 4) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['amount']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($return['data']['payFinishTime'])); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 5) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //传化
            if (11999 < $type && $type < 12999) {
                //读取配置
                $config = new TfConfigController();
                $h_merchant = $config->tf_merchant($store_id, $store_pid);
                if (!$h_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '传化商户号不存在';
                    return $this->return_data($re_data);
                }

                $h_config = $config->tf_config($config_id, $h_merchant->qd);
                if (!$h_config) {

                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '传化配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $data = [];
                $obj = new \App\Api\Controllers\Tfpay\PayController();
                $data['mch_id'] = $h_config->mch_id; //
                $data['pub_key'] = $h_config->pub_key; //
                $data['pri_key'] = $h_config->pri_key; //
                $data['sub_mch_id'] = $h_merchant->sub_mch_id; //
                $data['refund_trade_no'] = $out_trade_no; //
                $data['date'] = date('Y-m-d', time()); //
                $return = $obj->refund_query($data); //暂时用查询代替

                //退款成功
                if ($return["status"] == 4) {
                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $return['data']['refund_fee']; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', time()); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 5) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;
                    return $this->return_data($re_data);

                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;

                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //随行付支付退款
            if (12999 < $type && $type < 13999) {
                $config = new VbillConfigController();
                $vbill_config = $config->vbill_config($config_id);
                if (!$vbill_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '随行付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $vbill_merchant = $config->vbill_merchant($store_id, $store_pid);
                if (!$vbill_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '随行付商户号不存在';

                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Vbill\PayController();
                $data['notify_url'] = url('/api/vbill/refund_notify_url'); //回调地址
                $data['request_url'] = $obj->refund_url; //请求地址;
                $data['mno'] = $vbill_merchant->mno;
                $data['privateKey'] = $vbill_config->privateKey; //
                $data['sxfpublic'] = $vbill_config->sxfpublic; //
                $data['orgId'] = $vbill_config->orgId; //
                $data['out_trade_no'] = $order->out_trade_no;
                $return = $obj->refund_query($data);

                //退款成功
                if ($return["status"] == 1) {
                    $re_data['result_code'] = 'SUCCESS';
                    $re_data['return_msg'] = '退款成功';
                    $re_data['refundNo'] = $refundNo;
                    $re_data['refundTime'] = date('Y-m-d H:i:s', time());
                    $re_data['refund_count'] = '1';

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $refundNo; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $refundNo; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $order->total_amount; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', time()); //否,String(14),退款时间,yyyyMMddHHmmss
                } //等待付款
                elseif ($return["status"] == 2) {
                    $re_data['result_code'] = 'USERPAYING';
                    $re_data['return_msg'] = '正在查询退款中';
                    $re_data['outTradeNo'] = $order->qwx_no;

                    return $this->return_data($re_data);
                } //订单失败关闭
                elseif ($return["status"] == 3) {
                    //其他情况
                    $message = '订单支付失败';
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                } else {
                    //其他情况
                    $message = $return['message'];
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = $message;
                }
            }

            //海科融通 退款查询
            if (21999 < $type && $type < 22999) {
                //读取配置
                $config = new HkrtConfigController();
                $hkrt_config = $config->hkrt_config($config_id);
                if (!$hkrt_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '海科融通配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $hkrt_merchant = $config->hkrt_merchant($store_id, $store_pid);
                if (!$hkrt_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '海科融通商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Hkrt\PayController();
                $hkrt_return_data = [
                    'access_id' => $hkrt_config->access_id,
                    'refund_no'  => $refundNo, //退款订单号,refund_no和 out_refund_no和channel_trade_no必传其中一个，三个都传则以refund_no为准，推荐使用refund_no
                    'access_key' => $hkrt_config->access_key
                ];
//                Log::info('收钱啦-海科融通-退款查询-入参');
//                Log::info($hkrt_return_data);
                $return = $obj->refund_query($hkrt_return_data); //0-系统错误 1-成功 2-失败 3-未知
//                Log::info('收钱啦-海科融通-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $hkrt_refund_amount = $return['data']['refund_amount']; //退款金额
                    $hkrt_total_amount = $return['data']['total_amount']; //原消费交易总金额
                    $hkrt_remanent_amount = $return['data']['remanent_amount']; //剩余可退款金额
                    $hkrt_refund_no = $return['data']['refund_no']; //SaaS平台的退款订单编号
                    $hkrt_return_time = $return['data']['trade_end_time']; //SaaS平台交易完成时间，交易完成以后会返回

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $hkrt_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $hkrt_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $hkrt_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $hkrt_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //易生支付 退款查询
            if (in_array($type,[21001,21002,21004,61001,61002,61004])) {
                    //读取配置
                $version="easypay";
                if(in_array($type,[61001,61002,61004])){
                    $version="easypaya";
                }
                $config = new EasyPayConfigController();
                $easypay_config = $config->easypay_config($config_id);
                if (!$easypay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '易生支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $easypay_merchant = $config->easypay_merchant($store_id, $store_pid,$version);
                if (!$easypay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '易生支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Easypay\PayController();
                $easypay_return_data = [
                    'channel_id' => $easypay_config->channel_id,
                    'mer_id' => $easypay_merchant->termMercode,
                    'device_id' => $easypay_merchant->termTermcode,
                    'out_trade_no' => $order->out_trade_no,
                    "private_key"=>$easypay_config->private_key
                ];
//                Log::info('收钱啦-易生支付-退款查询-入参');
//                Log::info($easypay_return_data);
                $return = $obj->order_query($easypay_return_data); //-1 系统错误 0-其他 1-成功 2-下单失败
//                Log::info('收钱啦-易生支付-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $easypay_refund_no = $return['data']['oriwtorderid']; //易生退货单号
                    $easypay_refund_amount = $order->total_amount; //退款金额
                    $easypay_total_amount = $order->total_amount; //原消费交易总金额
                    $easypay_return_time = $order->pay_time; //交易完成时间

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $easypay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $easypay_refund_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $easypay_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $easypay_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //联动优势 退款查询
            if (4999 < $type && $type < 5999) {
                $config = new LinkageConfigController();
                $linkage_config = $config->linkage_config($config_id);
                if (!$linkage_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '联动优势支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $linkage_merchant = $config->linkage_merchant($store_id, $store_pid);
                if (!$linkage_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '联动优势支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new \App\Api\Controllers\Linkage\PayController();
                $linkage_return_data = [
                    'channel_id' => $linkage_config->channel_id,
                    'mer_id' => $linkage_merchant->termMercode,
                    'device_id' => $linkage_merchant->termTermcode,
                    'out_trade_no' => $order->out_trade_no
                ];
//                Log::info('收钱啦-联动优势支付-退款查询-入参');
//                Log::info($linkage_return_data);
                $return = $obj->refund_query($linkage_return_data); //-1系统错误；0-其他；1-成功；2-验签失败；3-失败；4-处理中
//                Log::info('收钱啦-联动优势支付-退款查询');
//                Log::info($return);

                //退款请求成功
                if ($return['status'] == '1') {
                    $linkage_refund_no = $return['data']['orderNo']; //退款流水号
                    $linkage_trade_no = $return['data']['transactionId']; //联动流水号
                    $linkage_refund_amount = $return['data']['txnAmt']; //退款金额
                    $linkage_total_amount = $order->total_amount; //原消费交易总金额
                    $linkage_return_time = $order->pay_time; //交易完成时间

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $linkage_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $linkage_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $linkage_refund_amount * 100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', $linkage_return_time); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //威富通 退款查询
            if (26999 < $type && $type < 27999) {
                $version="v1";
                if(in_array($type,[27101, 27102, 27103, 27104, 27105, 27107])){
                    $version="v2";
                }
                $config = new WftPayConfigController();
                $wftpay_config = $config->wftpay_config($config_id,$version);
                if (!$wftpay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '威富通支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $wftpay_merchant = $config->wftpay_merchant($store_id, $store_pid,$version);
                if (!$wftpay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '威富通支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new WftpayPayController();
                $wftpay_return_data = [
                    'mch_id' => $wftpay_merchant->mch_id,
                    'out_trade_no' => $order->out_trade_no,
                    'private_rsa_key' => $wftpay_config->private_rsa_key,
                    'public_rsa_key' => $wftpay_config->public_rsa_key
                ];
//                Log::info('威富通支付-收钱啦-退款查询-入参');
//                Log::info($wftpay_return_data);
                $return = $obj->refund_query($wftpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('威富通支付-收钱啦-退款查询');
//                Log::info($return);
                //退款请求成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $wftpay_refund_no = $return['data']['out_refund_no_'.$refund_count] ?? ''; //商户退款单号
                    $wftpay_trade_no = $return['data']['out_refund_id_'.$refund_count] ?? ''; //第三方退款单号
                    $wftpay_refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100): $order->total_amount; //退款总金额,单位为分,可以做部分退款
                    $wftpay_total_amount = $order->total_amount; //原消费交易总金额
                    $wftpay_return_time = $order->pay_time; //交易完成时间
                    $pay_time = isset($return['data']['refund_time_'.$refund_count]) ? date('Y-m-d H:i:s', strtotime($return['data']['refund_time_'.$refund_count])): ''; //退款时间

                    if ($order->pay_status != 6) {
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '退款成功',
                            'refund_no' => $wftpay_refund_no,
                            'refund_amount' => $wftpay_refund_amount
                        ];
                        if ($pay_time) $insert_data['pay_time'] = $pay_time;
                        $this->update_day_order($insert_data, $out_trade_no, '');

                        //退款成功后的动作
                        $refund_order_obj = RefundOrder::where('out_trade_no', $out_trade_no)->first();
                        if (!$refund_order_obj) {
                            $return_data = [
                                'out_trade_no' => $out_trade_no,
                                'trade_no' => $order->trade_no,
                                'store_id' => $order->store_id,
                                'merchant_id' => $order->merchant_id,
                                'type' => $order->ways_type,
                                'ways_source' => $order->ways_source,
                                'refund_amount' => $wftpay_refund_amount,
                                'refund_no' => $wftpay_refund_no ?? $wftpay_trade_no
                            ];
                            RefundOrder::query()->create($return_data);
                            RefundSuccessAction::action([
                                'out_trade_no'=>$out_trade_no,
                                'refund_no' => $wftpay_refund_no ?? $wftpay_trade_no, //联动流水号
                            ]);
                        }
                    }

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $wftpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $wftpay_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $wftpay_refund_amount*100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($wftpay_return_time)); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }

            //汇旺财 退款查询
            if (27999 < $type && $type < 28999) {
                $config = new HwcPayConfigController();
                $hwcpay_config = $config->hwcpay_config($config_id);
                if (!$hwcpay_config) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '汇旺财支付配置不存在请检查配置';
                    return $this->return_data($re_data);
                }

                $hwcpay_merchant = $config->hwcpay_merchant($store_id, $store_pid);
                if (!$hwcpay_merchant) {
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '汇旺财支付商户号不存在';
                    return $this->return_data($re_data);
                }

                $obj = new HwcPayPayController();
                $hwcpay_return_data = [
                    'mch_id' => $hwcpay_merchant->mch_id,
                    'out_trade_no' => $order->out_trade_no,
                    'private_rsa_key' => $hwcpay_config->private_rsa_key,
                    'public_rsa_key' => $hwcpay_config->public_rsa_key
                ];
//                Log::info('汇旺财支付-收钱啦-退款查询-入参');
//                Log::info($hwcpay_return_data);
                $return = $obj->refund_query($hwcpay_return_data); //0-系统错误 1-成功 2-退款失败 3-退款处理中 4-退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败
//                Log::info('汇旺财支付-收钱啦-退款查询');
//                Log::info($return);
                //退款请求成功
                if ($return['status'] == 1) {
                    $refund_count = $return['data']['refund_count']-1; //退款记录数
                    $hwcpay_refund_no = $return['data']['out_refund_no_'.$refund_count]; //商户退款单号
                    $hwcpay_trade_no = $return['data']['out_refund_id_'.$refund_count]; //第三方退款单号
                    $hwcpay_refund_amount = isset($return['data']['refund_fee_'.$refund_count]) ? ($return['data']['refund_fee_'.$refund_count] /100):$order->total_amount; //退款总金额,单位为分,可以做部分退款
                    $hwcpay_total_amount = $order->total_amount; //原消费交易总金额
                    $hwcpay_return_time = $order->pay_time; //交易完成时间
                    $pay_time = isset($return['data']['refund_time_'.$refund_count]) ? date('Y-m-d H:i:s', strtotime($return['data']['refund_time_'.$refund_count])): ''; //退款时间

                    if ($order->pay_status != 6) {
                        $insert_data = [
                            'status' => '6',
                            'pay_status' => 6,
                            'pay_status_desc' => '退款成功',
                            'refund_no' => $hwcpay_refund_no,
                            'refund_amount' => $hwcpay_refund_amount
                        ];
                        if ($pay_time) $insert_data['pay_time'] = $pay_time;
                        $this->update_day_order($insert_data, $out_trade_no, '');

                        //退款成功后的动作
                        $refund_order_obj = RefundOrder::where('out_trade_no', $out_trade_no)->first();
                        if (!$refund_order_obj) {
                            $return_data = [
                                'out_trade_no' => $out_trade_no,
                                'trade_no' => $order->trade_no,
                                'store_id' => $order->store_id,
                                'merchant_id' => $order->merchant_id,
                                'type' => $order->ways_type,
                                'ways_source' => $order->ways_source,
                                'refund_amount' => $hwcpay_refund_amount,
                                'refund_no' => $hwcpay_refund_no ?? $hwcpay_trade_no
                            ];

                            RefundOrder::query()->create($return_data);
                            RefundSuccessAction::action([
                                'out_trade_no'=>$out_trade_no,
                                'refund_no' => $hwcpay_refund_no ?? $hwcpay_trade_no, //联动流水号
                            ]);

                        }
                    }

                    $refund_count = 1;
                    $refund_count_num = $refund_count - 1;
                    $re_data['refund_status_'.$refund_count_num] = 'SUCCESS'; //String(16),退款状态：SUCCESS—退款成功；FAIL—退款失败；PROCESSING—退款处理中；NOTSURE—未确定，需要商户原退款单号重新发 起 ；CHANGE—转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者转账的方式进行退款。
                    $re_data['transaction_id'] = $transaction_id; //String(32),平台交易单号
                    $re_data['out_trade_no'] = $out_trade_no; //String(32),商户订单号
                    $re_data['refund_count'] = $refund_count; //int,退款记录数
                    $re_data['out_refund_no_'.$refund_count_num] = $hwcpay_refund_no; //String(32),商户退款单号
                    $re_data['refund_id_'.$refund_count_num] = $hwcpay_trade_no; //String(32),平台退款单号
                    $re_data['refund_channel_'.$refund_count_num] = 'ORIGINAL'; //String(16),原路退款，默认
                    $re_data['refund_fee_'.$refund_count_num] = $hwcpay_refund_amount*100; //int,退款总金额,单位为分,可以做部分退款
                    $re_data['refund_time_'.$refund_count_num] = date('YmdHis', strtotime($hwcpay_return_time)); //否,String(14),退款时间,yyyyMMddHHmmss
                } else {
                    //其他情况
                    $re_data['result_code'] = 'FALL';
                    $re_data['return_msg'] = '退款失败';
                    $re_data['refundNo'] = $refundNo;
                }
            }
            return $this->return_data($re_data);
        } catch (\Exception $e) {
            Log::info('收钱啦-退款查询error');
            Log::info($e->getMessage() .' | '. $e->getFile() .' | '. $e->getLine());
            $re_data = [
                'return_code' => 'FALL',
                'return_msg' => $e->getMessage() .' | '. $e->getLine()
            ];
        }
        return $this->return_data($re_data);
    }


    //获取俩时间间隔日期
    public function getDateFromRange($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        $days = ($etimestamp-$stimestamp) / 86400; // 计算日期段内有多少天
        $date = array(); // 保存每天日期

        for($i = 0; $i < $days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }
        return $date;
    }

    /**
     * 日均收款
     * 2022-04-21 15:40
     */
    public function avg_daily_payment(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex = $request->get('curHdIndex', '');
        $store_id = $request->get('store_id', '');

        $store = DB::table('stores')->where('store_id', $store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
        $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
        if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
            $store_ids[0] = $store->store_id;
            $p_stores = json_decode($p_stores, true);
            foreach($p_stores as $k1 => $v1){
                $store_ids[] = $v1['store_id'];
            }
        }else{
            $store_ids[0] = $store->store_id;
        }
        if($curHdIndex == 1){ // 今日
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
            $start_date=date('Y-m-d');
            $end_date=date('Y-m-d');
            $total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount'); // 总收款
            $fenrun_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount'); // 分润手续费
            $server_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('rata_money')->sum('rata_money'); // 服务费手续费
            $fee_amount = bcadd($fenrun_amount,$server_amount,2);
            $refund_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 总退款
            $total_num = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count(); // 总收款笔数
            $refund_num = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->count(); // 总退款笔数
            $total_amount=bcsub($total_amount,$refund_amount,2);
            $final_amount = bcsub($total_amount, ($fee_amount + $refund_amount), 2);
            $real_amount = bcsub($total_amount, $refund_amount, 2);

            $date = date('Y-m-d');
            $data = [
                '0' => [
                    'store_name' => '交易日期',
                    'merchant_name' => $date,
                    'total_num' => '交易笔数：' . $total_num,
                    'money_name' => '入账金额',
                    'total_amount' => $total_amount
                ]
            ];
            $return = array('total_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data, 'start_date' => $start_date, 'end_date' => $end_date);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
        if($curHdIndex == 2){ // 昨日
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $start_date=date('Y-m-d', strtotime("-1 day"));
            $end_date=date('Y-m-d', strtotime("-1 day"));
            
            $time_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
            $time_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
        }else if($curHdIndex == 3){ // 上周
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            
            $time_start = date('Y-m-d 00:00:00', strtotime('last week'));
            $time_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
        }else if($curHdIndex == 4){ // 本月
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d', strtotime("-1 day"));

            $time_start = date('Y-m-d 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $time_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
        }else if($curHdIndex == 5){ // 上月
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $start_date=date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
            $end_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
            
            $time_start = date('Y-m-d 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
            $time_end = date('Y-m-d 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
        }else if($curHdIndex == 6){ // 上月
            $start_data = $request->get('start_data', '');
            $end_data = $request->get('end_data', '');
            $start_date=$start_data;
            $end_date=$end_data;
            
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
            

            $time_start = $start_data . ' 00:00:00';
            $time_end = $end_data . ' 23:59:59';
        }
        $date = $this->getDateFromRange($time_start, $time_end); // 获取俩时间间隔日期
        if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
            $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_amount']);
            $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_amount']);
            $ways_amount->unionAll($ways_amount1);
            $store_amount=0;
            foreach ($ways_amount->get() as $obj) {
                $store_amount += $obj->order_amount;
            }
            $store_amount=$store_amount/100;
            
            $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
            $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['refund_amount']);
            $refund_amount_zong->unionAll($refund_amount1);
            $refund_amount=0;
            foreach ($refund_amount_zong->get() as $obj) {
                $refund_amount += $obj->refund_amount;
            }
            $refund_amount=$refund_amount/100;
            
            $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['order_total']);
            $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['order_total']);
            $order_total_zong->unionAll($order_total_zong1);
            $order_total=0;
            foreach ($order_total_zong->get() as $obj) {
                $order_total += $obj->order_total;
            }
            
            $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select(['receive_fee']);
            $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id',$store_id)->select(['receive_fee']);
            $receive_fee_zong->unionAll($receive_fee_zong1);
            $receive_fee=0;
            foreach ($receive_fee_zong->get() as $obj) {
                $receive_fee += $obj->receive_fee;
            }
            $receive_fee=$receive_fee/100;
        }else{
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
            $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('order_total')->sum('order_total');
            $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->where('store_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
        }
        $total_amount = $store_amount;
        $total_num = $order_total;
        $refund_amount = $refund_amount;
        $refund_num = '0';
        $fee_amount = $receive_fee;
        $final_amount = bcsub($total_amount, ($fee_amount + $refund_amount), 2);
        $real_amount = bcsub($total_amount,  $refund_amount, 2);
        foreach($date as $k => $v){
            $data[$k]['store_name'] = '交易日期';
            $data[$k]['merchant_name'] = $v;
            $data[$k]['money_name'] = '入账金额';
            $where1[] = ['bill_date', '>=', strtotime($v.' 00:00:00')];
            $where1[] = ['bill_date', '<=', strtotime($v.' 23:59:59')];

            $table='wft_stores_orders_' . date('Ym', strtotime($v)) . '_bill';
            $store_amount=DB::connection('old_mysql')->table($table)->where($where1)->where('store_id',$store_id)->select('order_amount')->sum('order_amount')/100;
            $order_total=DB::connection('old_mysql')->table($table)->where($where1)->where('store_id',$store_id)->select('order_total')->sum('order_total');
            $data[$k]['total_amount'] = $store_amount; // 门店总金额
            // $data[$k]['total_num'] = DB::table('company_day_commission')->whereIn('store_id', $store_ids)->where($where)->where('user_id',$token_user_id)->select('total_num')->sum('total_num'); // 门店总笔数
            $data[$k]['total_num'] = '交易笔数：' . $order_total . '笔';
            unset($where1);
        }
        $return = array('total_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data, 'start_date' => $start_date, 'end_date' => $end_date);
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($return);
    }

    private function getAgentSubId($id, &$agent_list)
    {
        $array = [];
        if ($agent_list) {
            foreach ($agent_list as $_id => $pid) {
                if ($pid == $id) {
                    $array[] = $_id;
                    $_array = $this->getAgentSubId($_id, $agent_list);
                    if (is_array($_array)) {
                        $array = array_merge($array, $_array);
                    }
                }
            }
        }
        return $array;
    }

    private function getMonthDifference($start, $end)
    {
        $years = date('Y', $end) - date('Y', $start);
        $monthTotal = $years * 12 + date('m', $end) - date('m', $start);
        return $monthTotal;
    }

    public function payment_channel(Request $request)
    {
        $format = [];
        $curHdIndex = $request->get('curHdIndex', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start = $request->get('start_date', '');
        $date_end = $request->get('end_date', '');
        try {
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当天");
            }
            $cache_key = 'agent:sub_list';
            $db = DB::connection();
            $agentSubList = Cache::get($cache_key,false);
            if ($agentSubList==false) {
                $agentSubList = [];
                $agentList = $db->table('users')->pluck('pid', 'id');
                foreach ($agentList as $_id => $pid) {
                    $agentSubList[$_id] = $this->getAgentSubId($_id, $agentList);
                }
                if (is_array($agentSubList) && count($agentSubList) > 0) {
                    Cache::add($cache_key, $agentSubList, 120);
                }
            }
            $fee_amount = '0.00';
            $total_amount = '0.00';
            $refund_amount = '0.00';
            $commission_money = '0.00';
            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'company')->toArray();
            $company_list = $db->table('store_all_pay_way_lists')->whereIn('company', array_keys($user_rates))->pluck('company_desc', 'company')->toArray();
            $user_company = $db->table('user_rates')->where('user_id', $user_id)->groupBy('company')->pluck(DB::raw("GROUP_CONCAT(ways_type)"), 'company')->toArray();
            $merchant_list = [];
            if (is_array($user_rates)) {
                $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
                $agentIds = array_merge($agentSubList[$user_id], [$user_id]);
                foreach ($user_company as $company => $ways_type) {
                    if(!isset($company_list[$company])){
                         continue;
                    }
                    $company_amount = '0.00';
                    $company_total = 0;
                    $company_refund = '0.00';
                    $company_fee = '0.00';
                    $company_commission = '0.00';
                    $company_name = $company_list[$company];
                    $company_rates = explode(':', $user_rates[$company]);
                    $explode = explode(',', $ways_type);
                    $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
                    $pluck = DB::connection('old_mysql')->table($tableName)
                        ->whereIn('receive_code', $explode)
                        ->whereIn('sales_id', $agentIds)
                        ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                        ->select([
                            'receive_rate',
                            'receive_model',
                            DB::raw('sum(receive_fee) as receive_fee'),
                            DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                            DB::raw('sum(order_total) as order_total'),
                            DB::raw('sum(order_amount) as order_amount'),
                            DB::raw('sum(refund_total) as refund_total'),
                            DB::raw('sum(refund_amount) as refund_amount'),
                        ])
                        ->groupBy(Db::raw('receive_rate,receive_model'));
                    for ($i = 0; $i < $monthTotal; $i++) {
                        $num = $i + 1;
                        $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                        $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                        $union_pluck = DB::connection('old_mysql')->table($tableName)
                            ->whereIn('receive_code', $explode)
                            ->whereIn('sales_id', $agentIds)
                            ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                            ->select([
                                'receive_rate',
                                'receive_model',
                                DB::raw('sum(receive_fee) as receive_fee'),
                                DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                                DB::raw('sum(order_total) as order_total'),
                                DB::raw('sum(order_amount) as order_amount'),
                                DB::raw('sum(refund_total) as refund_total'),
                                DB::raw('sum(refund_amount) as refund_amount'),
                            ])
                            ->groupBy(Db::raw('receive_rate,receive_model'));
                        $pluck->unionAll($union_pluck);
                    }
                    foreach ($pluck->get() as $obj) {
                        $item = (array)$obj;
                        $user_rate = $company_rates[$item['receive_model'] - 1];
                        if ($user_rate >= 0 && $item['receive_rate'] > $user_rate) {
                            $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                            $difference = bcdiv($difference, 100, 2);
                            $company_commission = bcadd($company_commission, $difference, 2);
                        }
                        $company_amount = bcadd($company_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $company_total = bcadd($company_total, $item['order_total']);
                        $company_refund = bcadd($company_refund, bcdiv($item['refund_amount'], 100, 2), 2);
                        $company_fee = bcadd($company_fee, bcdiv($item['receive_fee'] - $item['receive_refund_fee'], 100, 2), 2);
                    }
                    $merchant_list[] = [
                        'company' => $company_name,
                        'total_amount' => $company_amount,
                        'total_count' => $company_total,
                        'refund_amount' => $company_refund,
                        'fee_amount' => $company_fee,
                        'commission_money' => $company_commission,
                    ];
                    $total_amount = bcadd($total_amount, $company_amount, 2);
                    $refund_amount = bcadd($refund_amount, $company_refund, 2);
                    $fee_amount = bcadd($fee_amount, $company_fee, 2);
                    $commission_money = bcadd($commission_money, $company_commission, 2);
                }
            }
            $format = [
                'total_amount' => bcsub($total_amount,$refund_amount,2),
                'refund_amount' => $refund_amount,
                'fee_amount' => $fee_amount,
                'commission_money' => $commission_money,
                'merchant_list' => $merchant_list,
            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }

    /**
     * 通道汇总
     * 2022-04-22 14:49
     */
    public function _payment_channel(Request $request){
        $curHdIndex = $request->get('curHdIndex', '');
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $date_start=$request->get('start_date', '');
        $date_end=$request->get('end_date', '');
        $company = Db::table('user_rates')->where('user_id', $user_id)->select('company')->distinct('company')->get(); // 获取代理开通的支付通道
        $company = json_decode($company, true);

        $company_array = [
            '0' => 'vbill',
            '1' => 'lianfu',
            '2' => 'nongjin',
            '3' => 'lianfuyoupay',
            '4' => 'wftpay',
            '5' => 'hwcpay',
            '6' => 'abc',
            '7' => 'pingan',
            '8' => 'wingpay',
            '9' => 'saobei',
            '10' => 'ccb',
            '11' => 'jiujiang',
            '12' => 'linkage',
            '13' => 'alipay',
            '14' => 'weixin',
            '15' => 'unionpay_merch'
        ];

        if ($curHdIndex == 1){
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
            $start_date=date('Y-m-d');
            $end_date=date('Y-m-d');
            $data = [];
            $total_amount = '0.00'; // 总收款
            $fenrun_amount = '0.00'; // 分润手续费
            $server_amount = '0.00'; // 服务费手续费
            $fee_amount = $fenrun_amount + $server_amount; // 总手续费
            $commission_money = '待结算'; // 佣金

            foreach ($company as $k => $v) {
                $data[$k]['company'] = $this->get_commany_name($v['company']);
                $data[$k]['total_amount'] = '0.00'; // 总金额
                $data[$k]['total_count'] = '0.00'; // 交易笔数
                $data[$k]['refund_amount'] = '0.00'; // 退款金额
                $data[$k]['fee_amount'] = '0.00'; // 总手续费
                $data[$k]['commission_money'] = '待结算'; // 佣金
            }

            $return = array('total_amount' => $total_amount, 'fee_amount' => $fee_amount, 'commission_money' => $commission_money, 'merchant_list' => $data,'start_date'=>$start_date,'end_date'=>$end_date);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
        if($curHdIndex == 2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime("-1 day"));
            $end_date=date('Y-m-d', strtotime("-1 day"));
            $start_commission=date('Y-m-d',strtotime("-1 day"));
            $end_commission=date('Y-m-d',strtotime("-1 day"));
        }else if($curHdIndex == 3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            $start_commission=date('Y-m-d', strtotime('last week'));
            $end_commission=date('Y-m-d', strtotime('this week -1 day'));
        }else if($curHdIndex == 4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d', strtotime("-1 day"));
            $start_commission=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_commission=date('Y-m-d', strtotime("-1 day"));
        }else if($curHdIndex == 5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];
            $start_date=date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
            $end_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
            $start_commission=date('Y-m-01', strtotime('-1 month'));
            $end_commission=date('Y-m-t', strtotime('-1 month'));
        }
        else if($curHdIndex == 6){
            $where[] = ['bill_date', '>=', strtotime($date_start.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($date_end.' 23:59:59')];
            $where_c[] = ['settling_day', '>=', $date_start];
            $where_c[] = ['settling_day', '<=', $date_end];
            $start_date=$date_start;
            $end_date=$date_end;
            $start_commission=$start_date;
            $end_commission=$end_date;
        }
        $user_ids = $this->getSubIds($user_id);
        $data = [];
        if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
            $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
            $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['order_amount']);
            $ways_amount->unionAll($ways_amount1);
            $store_amount=0;
            foreach ($ways_amount->get() as $obj) {
                $store_amount += $obj->order_amount;
            }
            $store_amount=$store_amount/100;
            
            $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
            $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
            $refund_amount_zong->unionAll($refund_amount1);
            $refund_amount=0;
            foreach ($refund_amount_zong->get() as $obj) {
                $refund_amount += $obj->refund_amount;
            }
            $refund_amount=$refund_amount/100;
        }else{
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $store_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
            $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
        }
        $fee_amount='0.00';
        $get_commission=$start_commission.','.$end_commission;
        $commission_money =DB::table('company_day_commission')->where($where_c)->where('user_id',$user_id)->select('commission_money')->sum('commission_money'); //总佣金

        
        foreach ($company as $k => $v) {
            if( in_array( $v['company'], $company_array ) ){
                $company_ways=DB::table('store_ways_desc')->where('company', $v['company'])->select('ways_type as receive_code')->get();
                $company_ways=json_decode($company_ways,true);
                unset($pluckArray);
                foreach ($company_ways as $key1=>$val1){
                    $pluckArray[$key1]=$val1['receive_code'];
                }
                $data[$k]['company'] = $this->get_commany_name($v['company']);
                // 总金额
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount_company=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount_company += $obj->order_amount;
                    }
                    $store_amount_company=$store_amount_company/100;
                    
                    $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['refund_amount']);
                    $refund_amount_zong->unionAll($refund_amount1);
                    $refund_amount_company=0;
                    foreach ($refund_amount_zong->get() as $obj) {
                        $refund_amount_company += $obj->refund_amount;
                    }
                    $refund_amount_company=$refund_amount_company/100;
                    
                    $order_total_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['order_total']);
                    $order_total_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['order_total']);
                    $order_total_zong->unionAll($order_total_zong1);
                    $order_total=0;
                    foreach ($order_total_zong->get() as $obj) {
                        $order_total += $obj->order_total;
                    }
                    
                    $receive_fee_zong=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['receive_fee']);
                    $receive_fee_zong1=DB::connection('old_mysql')->table($table1)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select(['receive_fee']);
                    $receive_fee_zong->unionAll($receive_fee_zong1);
                    $receive_fee=0;
                    foreach ($receive_fee_zong->get() as $obj) {
                        $receive_fee += $obj->receive_fee;
                    }
                    $receive_fee=$receive_fee/100;
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $store_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select('order_amount')->sum('order_amount')/100;
                    $refund_amount_company=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select('refund_amount')->sum('refund_amount')/100;
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select('order_total')->sum('order_total');
                    $receive_fee=DB::connection('old_mysql')->table($table)->where($where)->whereIn('receive_code',$company_ways)->whereIn('sales_id',$user_ids)->select('receive_fee')->sum('receive_fee')/100;
                }
                
                $data[$k]['total_amount'] = $store_amount_company;
                // 交易笔数
                $data[$k]['total_count'] = $order_total;
                // 退款金额
                $data[$k]['refund_amount'] = $refund_amount_company;
                // 总手续费
                $data[$k]['fee_amount'] = $receive_fee;
                // 佣金
                $data[$k]['commission_money'] = Db::table('company_day_commission')->where('company', $v['company'])->where($where_c)->where('user_id',$user_id)->select('commission_money')->sum('commission_money');
            }
        }
        $edit = array_column($data, 'total_amount');
        array_multisort($edit, SORT_DESC, $data);
        
        $return = array('total_amount' => bcsub($store_amount,$refund_amount,2), 'refund_amount' => $refund_amount, 'fee_amount' => $fee_amount, 'commission_money' => $commission_money, 'merchant_list' => $data,'start_date'=>$start_date,'end_date'=>$end_date);
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($return);
    }

    /**
     * 重置门店密码
     */
    public function resetpassword(Request $request){
        $token = $this->parseToken();
        // dump($token);die;
        // $data = $request->getContent();
        // $data = $this->xml_to_array($data);
        $user_login_id = $token->user_id;
        // dump($user_login_id);die;
        if( $user_login_id !== 1 ){
            return json_encode([
                'status' => 2,
                'message' => '暂无权限'
            ]);
        }
        // $store_id = $request->get('store_id', '');
        // $password = $request->get('password', '');
        $password = '000000';
        $merchant_id = $request->get('merchant_id', '');
        // if( strlen($password) < 6 ){
        //     return json_encode([
        //         'status' => 2,
        //         'message' => '密码长度不能低于6位'
        //     ]);
        // }
        $dataIN = [
            'password' => bcrypt($password),
        ];
        $user_info = Db::table('merchants')->where('id', $merchant_id)->first();
        // dump($merchant_id);die;

        $res = Db::table('merchants')->where('id', $merchant_id)->update(['password' => $dataIN['password']]);
        if ($res) {
            $data = [
                'status' => 1,
                'message' => '密码修改成功',
            ];
        } else {
            $data = [
                'status' => 2,
                'message' => '密码修改失败',
            ];
        }
        return json_encode($data);
    }

    /**
     * 所有门店
     * 2022-05-07 15:48
     */
    function all_stroes(Request $request){
//        $token_user_id = $this->parseToken()->user_id;
//        $user_ids = $this->getSubIds($token_user_id); // 获取代理下的用户
//        $obj = DB::table('stores')->whereIn('user_id', $user_ids)->where('pid', '=', 0)->select('store_id', 'store_name', 'id')->get(); // 获取代理下的门店

        try {
            $merchant_id = $this->parseToken()->merchant_id;

            $stores = MerchantStore::where('merchant_id', $merchant_id)->select('store_id')->get()->toArray();
//            dump($data);die;

            $obj = DB::table('stores');
            $obj->whereIn('store_id', $stores);

            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('id', 'asc')->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }

    /**
     * 查看门店的收银员列表
     * 2022-05-07 17:43
     */
    public function by_cashier(Request $request){
        $store_id = $request->get('store_id', ''); // 门店id

        $merchant = Db::table('merchant_stores as ms')->where('ms.store_id', $store_id)->leftJoin('merchants', 'ms.merchant_id', '=', 'merchants.id')->select('ms.merchant_id', 'merchants.name')->get(); // 门店下的收银员列表
//        dump($merchant);die;

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($merchant);
    }

    /**
     * 查看收银员的收款记录
     * 2022-05-09 15:13
     */
    public function view_cashier(Request $request){
        $merchant_id = $request->get('merchant_id', ''); // 收银员id
        $store_id = $request->get('store_id', ''); // 门店id
        $time_start = $request->get('time_start', ''); //
        $time_end = $request->get('time_end', ''); //
//        dump($time_start);
//        dump($store_id);die;
        if( $merchant_id !== 'undefined'){
            $where[] = ['merchant_id' , '=', $merchant_id]; // 收银员id
        }

        if( $time_start == 'undefined' || $time_end == 'undefined' ){
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
        }else{
            $where[] = ['created_at', '>=', $time_start];
            $where[] = ['created_at', '<=', $time_end];
        }
//        dump($store_id);die;

//        $order = Db::table('orders')->where($where)->where('store_id', $store_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source')->get();
        $obj = Db::table('orders')->where($where)->where('store_id', $store_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'out_trade_no');
        $this->t = $obj->count();
        $store_ids = $this->page($obj)->get();
        $store_ids = json_decode($store_ids, true);

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($store_ids);
    }

    /**
     * 新增商户(列表)
     * 2022-05-12 10:03
     */
    public function add_merchant(Request $request){
        try{
            $user = $this->parseToken();
            $user_id = $request->get('user_id', $user->user_id);
            $time_start = $request->get('time_start', '');//关键词
            $time_end = $request->get('time_end', '');//关键词
            $store_name = $request->get('store_name', '');//关键词
            $province_code = $request->get('province_code');//状态
            $city_code = $request->get('city_code');//状态
            $area_code = $request->get('area_code');//状态
            $status = $request->get('status');//状态
            $pid = $request->get('pid', 0);//主店ID
            $is_delete = $request->get('is_delete', 0);//
            $is_close = $request->get('is_close', 0);//
            $curHdIndex = $request->get('curHdIndex', '1');

            $where = [];
//            $where[] = ['stores.pid', '=', $pid];
//            $where[] = ['stores.is_delete', '=', $is_delete];
//            $where[] = ['stores.is_close', '=', $is_close];

            if ($curHdIndex == 1) {
                $where[] = ['stores.created_at', '>=', date('Y-m-d') . ' 00:00:00'];
                $where[] = ['stores.created_at', '<=', date('Y-m-d') . ' 23:59:59'];
            }else if($curHdIndex == 2){
                $where[] = ['stores.created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
                $where[] = ['stores.created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];
            }else if($curHdIndex == 3){
                $where[] = ['stores.created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
                $where[] = ['stores.created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];
            }else if($curHdIndex == 4){
                $where[] = ['stores.created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                $where[] = ['stores.created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];
            }else if($curHdIndex == 5){
                $where[] = ['stores.created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
                $where[] = ['stores.created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];
            }
//            dump($where);die;
            if ($status) {
                $where[] = ['stores.status', '=', $status];
            }
            if ($province_code) {
                $where[] = ['stores.province_code', '=', $province_code];
            }
            if ($city_code) {
                $where[] = ['stores.city_code', '=', $city_code];
            }
            if ($area_code) {
                $where[] = ['stores.area_code', '=', $area_code];
            }
            if ($time_start) {
                $time_start = date('Y-m-d 00:00:00', strtotime($time_start));
                $where[] = ['stores.created_at', '>=', $time_start];
            }
            if ($time_end) {
                $time_end = date('Y-m-d 23:59:59', strtotime($time_end));
                $where[] = ['stores.created_at', '<=', $time_end];
            }

            if (env('DB_D1_HOST')) {
                $obj = DB::connection("mysql_d1")->table("stores");
            } else {
//                $obj = DB::table('stores');
                $obj = new Store();
            }
            $obj = $obj->join('users', 'stores.user_id', 'users.id');

            if ($store_name) {
                if (is_numeric($store_name)) {
                    $where1[] = ['stores.store_id', 'like', '%' . $store_name . '%'];
                } else {
                    $where1[] = ['stores.store_name', 'like', '%' . $store_name . '%'];
                }
                $obj->where($where1)
                    ->whereIn('stores.user_id', $this->getSubIds($user_id))
                    ->with('store_pay_ways')
                    ->select('stores.*', 'users.name as user_name')
                    ->orderBy('stores.updated_at', 'desc');
            } else {
//                dump($where);die;
                $obj->where($where)
                    ->whereIn('stores.user_id', $this->getSubIds($user_id))
                    ->with('store_pay_ways')
                    ->select('stores.*', 'users.name as user_name')
                    ->orderBy('stores.updated_at', 'desc');
            }
            $this->t = $obj->count();
            $data = $this->page($obj)->get();
            $data=json_decode($data,true);
            foreach($data as $k=>$v){
                $store_pay_ways=DB::table('store_pay_ways')->where('store_id', $v['store_id'])->where('ways_source', 'weixin')->orderBy('sort', 'ASC')->get();
                foreach ($store_pay_ways as $key=>$val){
                    if($val->company=='vbill'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/suixingfu-tongdao@2x.png';
                    }else if($val->company=='alipay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/zhifubao-tongdao@2x.png';
                    }else if($val->company=='weixin'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/weixin-tongdao@2x.png';
                    }else if($val->company=='lianfu'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/lianfu.jpg';
                    }else if($val->company=='lianfuyoupay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/lianfuyoupay.jpg';
                    }else if($val->company=='linkage'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/linkage.jpg';
                    }else if($val->company=='wftpay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/wftpay.jpg';
                    }else if($val->company=='hwcpay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/hwcpay.jpg';
                    }else if($val->company=='nongjin'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/nongjin.jpg';
                    }else if($val->company=='abc'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/abc.jpg';
                    }else if($val->company=='unionpay_merch'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/unionpay_merch.jpg';
                    }else if($val->company=='wingpay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/wingpay.jpg';
                    }else if($val->company=='saobei'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/saobei.jpg';
                    }else if($val->company=='abc_quiet'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/abc_quiet.jpg';
                    }else if($val->company=='cool'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/cool.jpg';
                    }else if($val->company=='pingan'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/pingan.jpg';
                    }else if($val->company=='jiujiang'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/jiujiang.jpg';
                    }else if($val->company=='ccb'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/ccb.jpg';
                    }else if($val->company=='unionpay'){
                        $val->pay_amount_e='https://pay.zgjindoufu.com/upload/fuwushang/yunshanfu-tongdao@2x.png';
                    }
                }
                $data[$k]['store_pay_ways']=$store_pay_ways;
                $rate=DB::table('store_pay_ways')->where('store_id', $v['store_id'])->where('ways_source', 'weixin')->orderBy('sort', 'desc')->first();
                if(!empty($rate)){
                    $data[$k]['rate']=$rate->rate;
                }else{
                    $data[$k]['rate']='0.00';
                }
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }

    /**
     * 查看收银员的收银记录
     * 2022-05-12 14:15
     */
    public function view_cashier_records(Request $request){
        $merchant_id = $request->get('merchant_id', ''); // 收银员id
        $curHdIndex = $request->get('curHdIndex'); // 时间

        if ($curHdIndex == 1) {
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
        }else if($curHdIndex == 2){
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];
        }else if($curHdIndex == 3){
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];
        }else if($curHdIndex == 4){
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];
        }else if($curHdIndex == 5){
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];
        }

        $obj = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount', 'merchant_id')->orderBy('created_at', 'desc');
        $this->t = $obj->count();
        $store_ids = $this->page($obj)->get();
        $store_ids = json_decode($store_ids, true);

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($store_ids);
    }
    
    /**
     * 查看门店的收银记录
     * 2022-07-26 17:37
     */
    function view_store_records(Request $request){
        $merchant_id = $request->get('merchant_id', ''); // 收银员id
        $store_id = $request->get('store_id', ''); // 门店id
        $curHdIndex = $request->get('curHdIndex'); // 时间
        if($merchant_id=='undefined'){
            $store = DB::table('stores')->where('store_id', $store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
            $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
            if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
                $store_ids[0] = $store->store_id;
                $p_stores = json_decode($p_stores, true);
                foreach($p_stores as $k1 => $v1){
                    $store_ids[] = $v1['store_id'];
                }
            }else{
                $store_ids[0] = $store->store_id;
            }
            if ($curHdIndex == 1) {
                $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
                $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
                $order_data = Db::table('orders')->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6]) //成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                $refund_obj = Db::table('orders')->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('pay_status', 6) //退款
                    ->select('refund_amount');
                $total_amount = $order_data->sum('total_amount'); //交易金额
                $total_num = $order_data->count('total_amount'); //订单避暑
                $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                $refund_num = $refund_obj->count('total_amount'); //订单避暑
                $obj = Db::table('orders')->where($where)->whereIn('store_id', $store_ids)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount')->orderBy('created_at', 'desc');
                $this->t = $obj->count();
                $data = $this->page($obj)->get();
                $array=array('collectmoney'=>$data,'total_amount'=>$total_amount,'total_num'=>$total_num,'refund_amount'=>$refund_amount,'refund_num'=>$refund_num);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($array);

            }else if($curHdIndex == 2){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];

                $start_data = date('Y-m-d', strtotime("-1 day"));
                $end_data = date('Y-m-d', strtotime("-1 day"));
            }else if($curHdIndex == 3){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];

                $start_data = date('Y-m-d', strtotime('last week'));
                $end_data = date('Y-m-d', strtotime('this week -1 day'));
            }else if($curHdIndex == 4){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];

                $start_data = date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'));
                $end_data = date('Y-m-d' . ' 23:59:59', strtotime("-1 day"));
            }else if($curHdIndex == 5){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];

                $start_data = date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
                $end_data = date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
            }else if($curHdIndex == 6){
                $start_data = $request->get('start_data', ''); //
                $end_data = $request->get('end_data', ''); //

                $where[] = ['created_at', '>=', $start_data . ' 00:00:00'];
                $where[] = ['created_at', '<=', $end_data . ' 23:59:59'];

                if ($start_data != $end_data) {
                    $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                    if (!$date) {
                        $this->status = '2';
                        $this->message = '开始时间不能超过结束时间';
                        return $this->format(2);
                    }
                }
                //限制时间
                $date = ( strtotime($end_data) - strtotime($start_data) ) / 86400;
                $day = 31;
                if ($date > $day) {
                    $this->status = '2';
                    $this->message = "时间筛选不能超过 $day 天";
                    return $this->format(2);
                }
            }

            // 跨天操作
            $time_start_db = date('Ymd', strtotime($start_data));
            $time_end_db = date('Ymd', strtotime($end_data));;
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }
            if( $start_data >= date('Y-m-d', time()) && $end_data >= date('Y-m-d', time()) ){ // 今天
                $order_data = Db::table('orders')->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6]) //成功+退款
                ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                $refund_obj = Db::table('orders')->whereIn('store_id', $store_ids)->where($where)->where('pay_status', 6) //退款
                ->select('refund_amount');
                $total_amount = $order_data->sum('total_amount'); //交易金额
                $total_num = $order_data->count('total_amount'); //订单避暑
                $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                $refund_num = $refund_obj->count('total_amount'); //订单避暑

                $obj = Db::table('orders')->where($where)->whereIn('store_id', $store_ids)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount', 'merchant_id')->orderBy('created_at', 'desc');
                $this->t = $obj->count();
                $data = $this->page($obj)->get();
            }else{
                if( $is_ct_time ){
                    
                    $time = $this->getDateFromRanges($time_start_db, $time_end_db);
                    foreach( $time as $key => $val ){
                        $where = [];
                        
                        $where[] = ['created_at', '>=', $val . ' 00:00:00'];
                        $where[] = ['created_at', '<=', $val . ' 23:59:59'];
                        
                        $where_stores = '';
                        foreach( $store_ids as $k => $v ){
                            if($k == 0){
                                $where_stores = "'" . $v . "'";
                            }else{
                                $where_stores = $where_stores . ", '" . $v . "'";
                            }
                        }
                        $where[] = [ 'store_id', ' in ', '('.$where_stores.')' ];
                        
                        $wheres = '';
                        foreach ($where as $k => $v){
    //                        print_r( $v[0] );die;
                            if( $v[0] == 'store_id' ){
                                if($k == 0){
                                    $wheres = $wheres.' where `'.$v[0].'`'.$v[1].$v[2];
                                }else{
                                    $wheres = $wheres.' and `'.$v[0].'`'.$v[1].$v[2];
                                }
                            }else{
                                if($k == 0){
                                    $wheres = $wheres.' where `'.$v[0].'`'.$v[1]."'".$v[2]."'";
                                }else{
                                    $wheres = $wheres.' and `'.$v[0].'`'.$v[1]."'".$v[2]."'";
                                }
                            }
                        }
                        
                        
                        if( $val == date('Y-m-d', time()) ){ // 今天
                            $day_start = 'orders';
                        }else{
                            $day_start = 'orders_' . date( 'Ymd', strtotime($val) );
                        }

                        if($key == 0){
                            $test = '(select * from `' . $day_start . '`' . $wheres . ' )'; // 列表数据
                            $count = '(select count(*) from `' . $day_start . '`' . $wheres . ')'; // 总记录条数(分页)

                            $total_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and (`pay_status`=1 or `pay_status`=6) )'; // 总金额
                            $refund_amount = '(select sum(refund_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                            $refund_count = '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                            $get_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额

                        }else{
                            $test = $test . ' union all ' . '(select * from `' . $day_start . '`' . $wheres . ' )'; // 列表数据
                            $count = $count . ' union all ' . '(select count(*) from `' . $day_start . '`' . $wheres . ')'; // 总记录条数(分页)

                            $total_amount = $total_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and (`pay_status`=1 or `pay_status`=6) )'; // 总金额
                            $refund_amount = $refund_amount . ' union all ' . '(select sum(refund_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                            $refund_count = $refund_count . ' union all ' . '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                            $get_amount = $get_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额
                        }
                    }
                    $start = abs((abs(trim($request->get('p', 1))) - 1) * abs(trim($request->get('l', 25))));
                    $l = abs( trim($request->get('l', 25)) );
                    $test = $test . ' order by `created_at` desc limit ' . $start . "," . $l;

                    $data = DB::select($test);
                    $count = DB::select($count);
                    $total_amount = DB::select($total_amount);
                    $refund_amount = DB::select($refund_amount);
                    $refund_count = DB::select($refund_count);
                    $get_amount = DB::select($get_amount);

                    $count = json_decode( json_encode($count, true), true );
                    $total_amount = json_decode( json_encode($total_amount, true), true );
                    $refund_amount = json_decode( json_encode($refund_amount, true), true );
                    $refund_count = json_decode( json_encode($refund_count, true), true );
                    $get_amount = json_decode( json_encode($get_amount, true), true );

                    $total_num = 0;
                    foreach($count as $k => $v){
                        $total_num = $total_num + $v['count(*)'];
                    }

                    $total_amounts = 0;
                    foreach($total_amount as $k => $v){
                        $total_amounts = $total_amounts + $v['sum(total_amount)'];
                    }
                    $total_amount = number_format($total_amounts, 2, '.', '');

                    $refund_amounts = 0;
                    foreach($refund_amount as $k => $v){
                        $refund_amounts = $refund_amounts + $v['sum(refund_amount)'];
                    }
                    $refund_amount = number_format($refund_amounts, 2, '.', '');

//                    print_r( $refund_count );die;
                    $refund_num = 0;
                    foreach($refund_count as $k => $v){
//                        print_r( $v['count(total_amount)'] );die;
                        $refund_num = $refund_num + $v['count(total_amount)'];
                    }

//                    print_r( $refund_count );die;
                    $get_amounts = 0;
                    foreach($get_amount as $k => $v){
                        $get_amounts = $get_amounts + $v['sum(total_amount)'];
                    }
//                    print_r( $get_amounts );die;

                    $this->status = 1;
                    $this->message = '数据返回成功';
                    $this->needpage = 1;
                    $this->t = $total_num;
                }else{
                    $table = 'orders_' . $time_start_db;

                    $order_data = Db::table($table)->whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6]) //成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                    $refund_obj = Db::table($table)->whereIn('store_id', $store_ids)->where($where)->where('pay_status', 6) //退款
                    ->select('refund_amount');
                    $total_amount = $order_data->sum('total_amount'); //交易金额
                    $total_num = $order_data->count('total_amount'); //订单避暑
                    $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                    $refund_num = $refund_obj->count('total_amount'); //订单避暑
                    // dump($store_ids);die;
                    $obj = Db::table($table)->where($where)->whereIn('store_id', $store_ids)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount', 'merchant_id')->orderBy('created_at', 'desc');
                    $this->t = $obj->count();
                    // dump($this->t);die;
                    $data = $this->page($obj)->get();
//                    print_r( $data );die;
                }
            }
            $array=array('collectmoney'=>$data,'total_amount'=>$total_amount,'total_num'=>$total_num,'refund_amount'=>$refund_amount,'refund_num'=>$refund_num);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($array);
        }else{

            if ($curHdIndex == 1) {
                $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
                $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];

                $order_data = Db::table('orders')->where('merchant_id', $merchant_id)->where('store_id', $store_id)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6]) //成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                $refund_obj = Db::table('orders')->where('merchant_id', $merchant_id)->where('store_id', $store_id)
                    ->where($where)
                    ->where('pay_status', 6) //退款
                    ->select('refund_amount');
                $total_amount = $order_data->sum('total_amount'); //交易金额
                $total_num = $order_data->count('total_amount'); //订单避暑
                $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                $refund_num = $refund_obj->count('total_amount'); //订单避暑

                $obj = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->where('store_id', $store_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount')->orderBy('created_at', 'desc');
                $this->t = $obj->count();
                $data = $this->page($obj)->get();
                $array=array('collectmoney'=>$data,'total_amount'=>$total_amount,'total_num'=>$total_num,'refund_amount'=>$refund_amount,'refund_num'=>$refund_num);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($array);

            }else if($curHdIndex == 2){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];

                $start_data = date('Y-m-d', strtotime("-1 day"));
                $end_data = date('Y-m-d', strtotime("-1 day"));
            }else if($curHdIndex == 3){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];

                $start_data = date('Y-m-d', strtotime('last week'));
                $end_data = date('Y-m-d', strtotime('this week -1 day'));
            }else if($curHdIndex == 4){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];

                $start_data = date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'));
                $end_data = date('Y-m-d' . ' 23:59:59', strtotime("-1 day"));
            }else if($curHdIndex == 5){
                $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
                $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];

                $start_data = date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
                $end_data = date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
            }else if($curHdIndex == 6){
                $start_data = $request->get('start_data', ''); //
                $end_data = $request->get('end_data', ''); //
//                $start_data = '2022-04-01';
//                $end_data = '2022-04-03';

                $where[] = ['created_at', '>=', $start_data . ' 00:00:00'];
                $where[] = ['created_at', '<=', $end_data . ' 23:59:59'];

                if ($start_data != $end_data) {
                    $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                    if (!$date) {
                        $this->status = '2';
                        $this->message = '开始时间不能超过结束时间';
                        return $this->format(2);
                    }
                }
                //限制时间
                $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
                $day = 31;
                if ($date > $day) {
                    $this->status = '2';
                    $this->message = "时间筛选不能超过 $day 天";
                    return $this->format(2);
                }
            }
//            print_r( $curHdIndex );die;

            // 跨天操作
            $time_start_db = date('Ymd', strtotime($start_data));
            $time_end_db = date('Ymd', strtotime($end_data));;
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }

//            print_r( $is_ct_time );die;
            if( $start_data >= date('Y-m-d', time()) ){ // 今天
//                print_r( $store_id );die;
                $order_data = Db::table('orders')->where('merchant_id', $merchant_id)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6]) //成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                $refund_obj = Db::table('orders')->where('merchant_id', $merchant_id)->where('store_id', $store_id)->where($where)->where('pay_status', 6) //退款
                    ->select('refund_amount');
                $total_amount = $order_data->sum('total_amount'); //交易金额
                $total_num = $order_data->count('total_amount'); //订单避暑
                $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                $refund_num = $refund_obj->count('total_amount'); //订单避暑

                $obj = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->where('store_id', $store_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount', 'merchant_id')->orderBy('created_at', 'desc');
                $this->t = $obj->count();
                $data = $this->page($obj)->get();
            }else{
//                print_r( $is_ct_time );die;
                if( $is_ct_time ){
//                    print_r( $merchant_id );die;
                    $time = $this->getDateFromRanges($time_start_db, $time_end_db);
                    $where[] = [ 'store_id', '=', $store_id ];
                    $where[] = [ 'merchant_id', '=', $merchant_id ];
//                    print_r( $where );die;
                    $wheres = '';
                    foreach ($where as $k => $v){
//                        print_r( $v[0] );die;
                        if( $v[0] == 'store_id' ){
                            if($k == 0){
                                $wheres = $wheres.' where `'.$v[0].'`'.$v[1].$v[2];
                            }else{
                                $wheres = $wheres.' and `'.$v[0].'`'.$v[1].$v[2];
                            }
                        }else{
                            if($k == 0){
                                $wheres = $wheres.' where `'.$v[0].'`'.$v[1]."'".$v[2]."'";
                            }else{
                                $wheres = $wheres.' and `'.$v[0].'`'.$v[1]."'".$v[2]."'";
                            }
                        }
                    }
//                    print_r( $wheres );die;
                    foreach( $time as $k => $v ){
                        if( $v == date('Y-m-d', time()) ){ // 今天
                            $day_start = 'orders';
                        }else{
                            $day_start = 'orders_' . date( 'Ymd', strtotime($v) );
                        }

                        if($k == 0){
                            $test = '(select * from `' . $day_start . '`' . $wheres . ' order by `created_at` desc)'; // 列表数据 // (total_amount,refund_amount,receipt_amount,fee_amount,mdiscount_amount)
                            $count = '(select count(*) from `' . $day_start . '`' . $wheres . ')'; // 总记录条数(分页)

                            $total_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 总金额
                            $refund_amount = '(select sum(refund_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                            $refund_count = '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                            $get_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额

                        }else{
                            $test = $test . ' union all ' . '(select * from `' . $day_start . '`' . $wheres . ' order by `created_at` desc)'; // 列表数据
                            $count = $count . ' union all ' . '(select count(*) from `' . $day_start . '`' . $wheres . ')'; // 总记录条数(分页)

                            $total_amount = $total_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 总金额
                            $refund_amount = $refund_amount . ' union all ' . '(select sum(refund_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                            $refund_count = $refund_count . ' union all ' . '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                            $get_amount = $get_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额
//                            print_r( $refund_amount );die;
                        }
                    }
                    $start = abs((abs(trim($request->get('p', 1))) - 1) * abs(trim($request->get('l', 25))));
                    $l = abs( trim($request->get('l', 25)) );
                    $test = $test . ' limit ' . $start . "," . $l;

                    $data = DB::select($test);
                    $count = DB::select($count);
                    $total_amount = DB::select($total_amount);
                    $refund_amount = DB::select($refund_amount);
                    $refund_count = DB::select($refund_count);
                    $get_amount = DB::select($get_amount);

                    $count = json_decode( json_encode($count, true), true );
                    $total_amount = json_decode( json_encode($total_amount, true), true );
                    $refund_amount = json_decode( json_encode($refund_amount, true), true );
                    $refund_count = json_decode( json_encode($refund_count, true), true );
                    $get_amount = json_decode( json_encode($get_amount, true), true );

//                    print_r($refund_count);die;
                    $total_num = 0;
                    foreach($count as $k => $v){
//                        print_r($v['count(*)']);die;
                        $total_num = $total_num + $v['count(*)'];
                    }
//                    print_r($counts);die;

                    $total_amounts = 0;

                    foreach($total_amount as $k => $v){
                        $total_amounts = $total_amounts + $v['sum(total_amount)'];
                    }
                    $total_amount = number_format($total_amounts, 2, '.', '');

                    $refund_amounts = 0;
                    foreach($refund_amount as $k => $v){
                        $refund_amounts = $refund_amounts + $v['sum(refund_amount)'];
                    }
                    $refund_amount = number_format($refund_amounts, 2, '.', '');


                    $refund_num = 0;
                    foreach($refund_count as $k => $v){
//                        print_r( $v['count(total_amount)'] );die;
                        $refund_num = $refund_num + $v['count(total_amount)'];
                    }

//                    print_r( $refund_count );die;
                    $get_amounts = 0;
                    foreach($get_amount as $k => $v){
                        $get_amounts = $get_amounts + $v['sum(total_amount)'];
                    }
//                    print_r( $get_amounts );die;

                    $this->status = 1;
                    $this->message = '数据返回成功';
                    $this->needpage = 1;
                    $this->t = $total_num;
                }else{
                    $table = 'orders_' . $time_start_db;

                    $order_data = Db::table($table)->where('merchant_id', $merchant_id)->where('store_id', $store_id)->where($where)->whereIn('pay_status', [1, 6]) //成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');
                    $refund_obj = Db::table($table)->where('merchant_id', $merchant_id)->where('store_id', $store_id)->where($where)->where('pay_status', 6) //退款
                    ->select('refund_amount');
                    $total_amount = $order_data->sum('total_amount'); //交易金额
                    $total_num = $order_data->count('total_amount'); //订单避暑
                    $refund_amount = $refund_obj->sum('refund_amount'); //订单避暑
                    $refund_num = $refund_obj->count('total_amount'); //订单避暑

                    $obj = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->where('store_id', $store_id)->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount', 'merchant_id')->orderBy('created_at', 'desc');
                    $this->t = $obj->count();
                    $data = $this->page($obj)->get();
                }
            }

            $array=array('collectmoney'=>$data,'total_amount'=>$total_amount,'total_num'=>$total_num,'refund_amount'=>$refund_amount,'refund_num'=>$refund_num);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($array);
        }

    }

    public function export_rate(Request $request){
        $user_id=159;
        $tileArray = ['门店ID', '门店名称', '入驻时间'];
        $users=$this->getSubIds($user_id);
        $obj = DB::table('stores');
        $data = $obj->whereIn('user_id', $users)->where('pid',0)->select('store_id','store_name','created_at')->get();
        $dataArray=json_decode($data,true);
        ini_set('memory_limit', '512M');
        ini_set('max_execution_time', 0);
        ob_end_clean();
        ob_start();
        header("Content-Type: text/csv");
        header("Content-Disposition:filename=" . '11');
        $fp = fopen('php://output', 'w');
        fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));//转码 防止乱码(比如微信昵称(乱七八糟的))

        fputcsv($fp, []);
        fputcsv($fp, $tileArray);
        $index = 0;
        foreach ($dataArray as $item) {
            $item['store_id'] = $item['store_id'];
            $item['store_name'] = $item['store_name'];
            $item['created_at'] = $item['created_at'];
            $index++;
            fputcsv($fp, $item);
        }

        ob_flush();
        flush();
        ob_end_clean();
        die;
        fastcgi_finish_request();
        $store_id ='202242615830022533'; // store_id 202186113244626407
        $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
        $pstore=Db::table('stores')->where(['pid' => $store->id ])->get();
        if(empty($pstore[0]->store_id)){
            $store_ids[0]=$store_id;
        }else{
            $store_ids[0]=$store_id;
            foreach ($pstore as $k=>$v){
                $store_ids[$k+1]=$v->store_id;
            }
        }

        //充值总额
        $chongzhi=DB::table('fullmoney_log')->whereIn('store_id',$store_ids)->where('status',2)->select('total_price')->sum('total_price');
        DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$chongzhi));
//        if(!$store_id) return;
        // dump($store_id);die;

        $created_at_min = Db::table('skill_ratastore')->whereIn('store_id',$store_ids)->orderBy('created_at', 'asc')->value('created_at'); // 开始时间
        $created_at_max = Db::table('skill_ratastore')->whereIn('store_id',$store_ids)->orderBy('created_at', 'desc')->value('created_at'); // 结束时间
        $date = $this->getDateFromRange($created_at_min, '2022-05-15 23:59:59'); // 获取俩时间间隔日期
        foreach($date as $k => $v ){
            $where[] = ['created_at', '>=', $v.' 00:00:00']; // 每天开始时间
            $where[] = ['created_at', '<=', $v.' 23:59:59']; // 每天结束时间
            $data[$k]['day']=$v;
            $data[$k]['order_money'] = DB::table('skill_ratastore')->where($where)->whereIn('store_id',$store_ids)->select('order_money')->sum('order_money'); //
//            $order_count = DB::table('skill_ratastore')->where($where)->where('store_id', $store_id)->select('rata_money')->get(); // rata_money
//            $count = 0;
//            foreach( $order_count as $k => $v ){
////                dump($v->rata_money);die;
//                $count = $count + round( $v->rata_money, 2 ) * 100;
//            }
//            $data[$k]['rata_money_count'] = $count / 100;


//            dump($data);die;

            unset($where);
        }
        foreach($data as $k=>$v){
            $store=Db::table('stores')->where(['store_id' => $store_id ])->first();
            $rata_money=($v['order_money']/100)*$store->rata_store;
            $rata_money=round($rata_money,2);
            $end_money=$store->store_money-$rata_money;
            $rata=array(
                'count'=>$rata_money,
                'created_at'=>strtotime($v['day'].' 00:00:00'),
                'store_id'=>$store_id,
                'user_id'=>0,
                'settling_day'=>$v['day'],
                'before_money'=>$store->store_money,
                'end_money'=>$end_money,
                'order_count'=>$v['order_money']
            );
            DB::table('store_day_rate')->insert($rata);
            DB::table('stores')->where('store_id',$store_id)->update(array('store_money'=>$end_money));
        }
    }

    /**
     * 微信子商户支付参数配置 天阙
     * 2022-05-16 17:31
     */
    public function already_opened(Request $request){
        $store_id = $request->get('store_id', '');
        if(!$store_id) return;

        $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->get()->toArray();
//        dump($obj[0]);die;

        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($JdStoreItem[0]->config_id);
//        dump($vbill_config->sxfpublic);die;

        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->weixin_config;
//        dump($url);die;

//        $JdStoreItem[0]->mno = '399220517423529';
//        $JdStoreItem[0]->applicationId = 'f76c284da5644575aabe94043ccb637d';

        $childNo = '';

        // qr_pay
        $url = $obj->weixin_config;
        $data = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $JdStoreItem[0]->mno,
                'subMchId' => $childNo,
//                                'type'=>'jsapi',
                'type' => '03',
                'jsapiPath' => 'https://pretran.tianquetech.com/jsy/qrpay/'
            ],
        ];
//        dump($data);die;
        $wx_auth_res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
//        dump($wx_auth_res);die;

        //报备微信授权目录
        $url = $obj->weixin_config;
        $data = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $JdStoreItem[0]->mno,
                'subMchId' => $childNo,
//                                'type'=>'jsapi',
                'type' => '03',
                'jsapiPath' => env('APP_URL') . '/api/vbill/weixin/'
            ],
        ];
//        dump($data);die;
        $wx_auth_res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);

//        dump($wx_auth_res);die;

        // 报备天阙授权目录
        $data1 = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $JdStoreItem[0]->mno, // 399220517423529
                'subMchId' => $childNo,
//                                'type'=>'jsapi',
                'type' => '03',
                'applicationId' => $JdStoreItem[0]->applicationId, // f76c284da5644575aabe94043ccb637d
                'jsapiPath' => 'https://openapi.tianquetech.com/order/jsapiScan/'
            ],
        ];
        $data = $obj->execute($data1, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);

        //报备appid
        $data2 = [
            'orgId' => $vbill_config->orgId,
            'reqId' => time(),
            'version' => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType' => 'RSA',
            'reqData' => [
                'mno' => $JdStoreItem[0]->mno,
                'subMchId' => $childNo,
                'type' => '01',
                'accountType' => '00',
                'subAppid' => 'wx4e41b2f311ded3b1',
                'jsapiPath' => 'https://openapi.tianquetech.com/order/jsapiScan/'
            ],
        ];
        $data = $obj->execute($data2, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);

        $this->status = 1;
        $this->message = '设置成功';
        return $this->format($JdStoreItem[0]);
    }

    /**
     * 入驻审核结果通知接口 天阙
     * 2022-05-18 9:25
     */
    public function check_results(Request $request){
        $token = $this->parseToken();
        $store_id = $request->get('store_id', '');
        $company = $request->get('company', '');
        if(!$store_id) return;
        if($company=='wingpay'){
            $wing_stores = DB::table('store_pay_ways')->where(['store_id' => $store_id,'company'=>'wingpay'])->first(); // 查看门店审核状态
            if(empty($wing_stores)){
                return json_encode([
                    "status" => 2,
                    "message" => "请先开通通道",
                ]);
            }
            $store=DB::table('stores')->where([ 'store_id' => $store_id])->first();
            if($store->store_type=='3'){
                $solutionNo='PS11700';
            }else{
                $solutionNo='PS10418';
            }
            
            $obj = new \App\Api\Controllers\lianfu\PayController();
            $post_array=array('traceLogId'=>'wing'.time(),'loginNo'=>$store->people_phone);
            $url='https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/queryMerchantInputStatus';
            $res = $obj->queryMerchantInputStatus($post_array,$url);
            $res = json_decode($res, true);
            file_put_contents('b75685.log',var_export($res,true)."\r\n",FILE_APPEND);
            if($res['auditStatus'] == 'OPEN_ACCOUNT_SUCCESS'){
                return json_encode([
                    "status" => 2,
                    "message" => "审核中",
                    'data' => $res
                ]);
            }else if($res['auditStatus'] == 'AUDITED_SUCCESS'){
                $sub_ids = $this->getSubIds(469);
                if(in_array($store->user_id,$sub_ids)){
                    $wing_user_phone='15954359585';
                }else{
                   // $wing_user_phone='19359079377';
                   $wing_user_phone='18156861614';
                }
                // $wing_user_phone='19359079377';
                $obj = new \App\Api\Controllers\lianfu\PayController();
                $post_array=array(
                    'traceLogId'=>'wing'.time(),
                    'requestSystem'=>'AHHFWHPAY',
                    'agentMerchantCode'=>'3178035630163868',
                    'employeeId'=>$wing_user_phone,
                    'merchantCode'=>$res['merchantCode'],
                    'merchantType'=>'PERSON',
                    'solutionNo'=>$solutionNo,
                    'renewFlag'=>'TRUE',
                    'beginDate'=>date('Y-m-d H:i:s',time()),
                    'endDate'=>'2025-01-01 00:00:00'
                );
                 error_log(date('Y-m-d H:i:s')." 【翼支付进件查询】： ".json_encode($post_array)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");

                $url='https://mapi.bestpay.com.cn/mapi/agent/merchantinput/productContract';
                
                $return = $obj->productContract($post_array,$url);
                error_log(date('Y-m-d H:i:s')." 【翼支付进件查询rs】： ".json_encode($return)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
                if(isset($return['errorCode'])){
                    
                    return json_encode([
                        "status" => 2,
                        "message" => $return['errorMsg'],
                    ]);
                }else{
                    $wing=DB::table('wing_stores')->where(['store_id' => $store_id])->first();
                    if($wing){
                        DB::table('wing_stores')->where(['store_id' => $store_id])->update(['merchantNo' => $return['merchantCode'],'status'=>'1']);
                    }else{
                        DB::table('wing_stores')->where(['store_id' => $store_id])->insert(array('config_id'=>'1234','store_id'=>$store_id,'institutionCode'=>'3178035630163868','merchantNo'=>$return['merchantCode'],'created_at'=>date('Y-m-d H:i:s',time()),'updated_at'=>date('Y-m-d H:i:s',time()),'status'=>'1'));
                    }
                    $company_config=DB::table('company_config')->where(['store_id' => $store_id,'company' => 'wingpay'])->first();
                    
                    $data = [];
                    $data['store_id'] = $store_id;
                    $data['status'] = 1;
                    $data['rate'] = $company_config->configure_channel_fee;
                    $data['company'] = 'wingpay';
                    $data['status_desc'] = '开通成功';
                    $this->send_ways_data($data);
                    return json_encode([
                        "status" => 1,
                        "message" => "审核通过",
                        'data' => $res
                    ]);
                }
            }else if($res['auditStatus'] == 'ENABLE'){
                $wing=DB::table('wing_stores')->where(['store_id' => $store_id])->first();
                if($wing){
                    DB::table('wing_stores')->where(['store_id' => $store_id])->update(['merchantNo' => $res['merchantCode']]);
                }else{
                    DB::table('wing_stores')->where(['store_id' => $store_id])->insert(array('config_id'=>'1234','store_id'=>$store_id,'institutionCode'=>'3178035630163868','merchantNo'=>$res['merchantCode'],'created_at'=>date('Y-m-d H:i:s',time()),'updated_at'=>date('Y-m-d H:i:s',time()),'status'=>'1'));
                }
                $company_config=DB::table('company_config')->where(['store_id' => $store_id,'company' => 'wingpay'])->first();
                
                $data = [];
                $data['store_id'] = $store_id;
                $data['status'] = 1;
                $data['rate'] = $company_config->configure_channel_fee;
                $data['status_desc'] = '开通成功';
                $data['company'] = 'wingpay';
                $this->send_ways_data($data);
                
                return json_encode([
                    "status" => 1,
                    "message" => "审核通过",
                    'data' => $res
                ]);
            }else if($res['auditStatus'] == 'AUDITED_FAIL'){
                $message=isset($res['failureReason'])?$res['failureReason']:'审核失败';
                DB::table('store_pay_ways')->where([ 'store_id' => $store_id , 'company' => 'wingpay' ])->update([ 'status' => '3','status_desc'=>$message ]);
                return json_encode([
                    "status" => 2,
                    "message" =>$message,
                    'data' => $res
                ]);
            }
        }else{
            $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->get()->toArray();

            $config = new VbillConfigController();
            $vbill_config = $config->vbill_config($JdStoreItem[0]->config_id);
    
            $obj = new \App\Api\Controllers\Vbill\BaseController();
            $url = $obj->weixin_config;
    
            $url = $obj->open_query_store_url;
            $data = [
                'orgId' => $vbill_config->orgId,
                'reqId' => time(),
                'version' => '1.0',
                'timestamp' => date('Ymdhis', time()),
                'signType' => 'RSA',
                'reqData' => [
                    'applicationId' => $JdStoreItem[0]->applicationId, // f76c284da5644575aabe94043ccb637d
                ],
            ];
            $res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
            Log::channel("vbill")->info("check_results",[
                "url"=>$url,
                "req"=>$data,
                "res"=>$res
            ]);
            if($res['data']['respData']['taskStatus'] == "1"){
                $this->status = 1;
                $this->message = '入驻审核通过';
                
                Db::table('store_pay_ways')->where([ 'store_id' => $store_id,"company"=>"vbill" ])->update([ 'status' => 1, 'status_desc' => '开通成功' ]);
                //
                $mno=$res['data']['respData']['mno'];
                $repoInfo=$res['data']['respData']['repoInfo']??[];
                Log::channel("vbill")->info("check_results-2",[
                    "mno"=>$mno,
                    "repoInfo"=>$repoInfo
                ]);
                $weixin_mch_id=$alipay_mch_id=$yl_mch_id="";
                if(!empty($repoInfo)){
                    foreach($repoInfo as $k=>$v){
                        if($v["childNoType"]=="YL-MNO"){
                            $yl_mch_id=$v["childNo"];
                        }

                        if($v["childNoType"]=="ZFB"){
                            $alipay_mch_id=$v["childNo"];
                        }

                        if($v["childNoType"]=="WX"){
                            $weixin_mch_id=$v["childNo"];
                        }
                    }
                }
                //写入db
                $info=DB::table("vbill_sub_infos")->where([
                    'store_id' => $store_id,
                ])->first();
                if(empty($info)){
                    DB::table("vbill_sub_infos")->insert([
                        "mno"=>$mno,
                        "store_id"=>$store_id,
                        "weixin_mch_id"=>$weixin_mch_id,
                        "alipay_mch_id"=>$alipay_mch_id,
                        "yl_mch_id"=>$yl_mch_id,
                        "created_at"=>date("Y-m-d H:i:s",time()),
                        "updated_at"=>date("Y-m-d H:i:s",time())
                    ]);
                }else{
                    DB::table("vbill_sub_infos")->where("id",$info->id)->update([
                        "mno"=>$mno,
                        "store_id"=>$store_id,
                        "weixin_mch_id"=>$weixin_mch_id,
                        "alipay_mch_id"=>$alipay_mch_id,
                        "yl_mch_id"=>$yl_mch_id,
                        "created_at"=>date("Y-m-d H:i:s",time()),
                        "updated_at"=>date("Y-m-d H:i:s",time())
                    ]);
                }
                return $this->format($JdStoreItem[0]);
            }else{
                $this->status = 2;
                $msg = '';
                if (isset($res['data']['respData']['suggestion']) && !empty($res['data']['respData']['suggestion'])) {
	               $msg = $res['data']['respData']['suggestion'];
                }

                Db::table('store_pay_ways')->where([ 'store_id' => $store_id, "company"=>"vbill" ])
                    ->update([ 'status' => 3, 'status_desc' => '开通失败:'.$msg ]);

                $this->message = '入审核驻失败--'.$msg;
                return $this->format($JdStoreItem[0]);
            }
        }
        
    }
    
    /**
     * 入驻审核结果通知接口 天阙
     * 2022-05-18 9:25
     */
    public function vbill_del(Request $request){
        $store_id = $request->get('store_id', '');
        $company= $request->get('company', '');
        $pass= $request->get('pass', '');
        $pash = $request->path();
        $pass = $request->get('pass', '');
        $pass = substr(base64_decode($pass), 0, -5);
        $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
        $pass_verify = json_decode($pass_verify, true);
        if( $pass_verify['status'] == '1'){
            $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            $remark = '清除通道: 门店id: ' . $store_id . '通道为: ' . $company;
            $this->operation_log($this->parseToken()->user_id, 30, $remark , $pass_id);
        }else{
            return json_encode(['status' => 2, 'message' => '验证不通过', 'data' => []]);
        }
        
        if($company !='vbill'){
            $company_config=DB::table('company_config')->where('store_id', $store_id)->where('company', $company)->first();
            if(empty($company_config)){
                return json_encode(['status' => 2, 'message' => '无通道配置,无法清楚', 'data' => []]);
            }
            if($company_config->model=='4'){
                DB::table('company_config')->where('store_id', $store_id)->where('company', $company)->delete();
                DB::table("store_pay_ways")->where('store_id', $store_id)->where('company',$company)->delete();
                DB::table('server_stores')->where('store_id', $store_id)->where('company', $company)->delete();
                DB::table('stores')->where('store_id', $store_id)->update(array('rata_store'=>'0.00','rata_status'=>'0'));
            }else if($company_config->model=='3'){
                DB::table("store_pay_ways")->where('store_id', $store_id)->where('company',$company)->delete();
                DB::table('company_config')->where('store_id', $store_id)->where('company', $company)->delete();
            }else if($company_config->model=='2'){
                DB::table("store_pay_ways")->where('store_id', $store_id)->where('company',$company)->delete();
                DB::table('company_config')->where('store_id', $store_id)->where('company', $company)->delete();
            }else if($company_config->model=='1'){
                DB::table("store_pay_ways")->where('store_id', $store_id)->where('company',$company)->delete();
                DB::table('company_config')->where('store_id', $store_id)->where('company', $company)->delete();
                DB::table('stores')->where('store_id', $store_id)->update(array('rata_store'=>'0.00','rata_status'=>'0'));
            }
            $this->status = 1;
            $this->message = '清除成功';
            return $this->format();
        }else{
            DB::table("vbill_stores")->where(['store_id' => $store_id])->delete();
            DB::table("store_pay_ways")->where(['store_id' => $store_id])->where('company','vbill')->delete();
            DB::table("company_config")->where(['store_id' => $store_id])->where('company','vbill')->delete();
            DB::table('server_stores')->where('store_id', $store_id)->where('company', "vbill")->delete();
            $this->status = 1;
            $this->message = '清除成功';
            return $this->format();
        }
    }
    
    public function mechanism_merchant(Request $request){
        // print_r(2);die;
        $data = $request->getContent();
        $data = json_decode($data, true);
    }
    
    function mechanism_merchant_add(Request $request){
        $store_id = $request->get('store_id', ''); // 系统门店id
        print_r(3);die;
    }
    
    /**
     * 查看收银员的收银记录
     * 2022-06-20 16:09
     */
//     public function merchant_bill(Request $request){
//         $merchant_id = $request->get('merchant_id', ''); // 收银员id
//         $curHdIndex = $request->get('curHdIndex'); // 时间
// //        print_r($curHdIndex);die;
//         if ($curHdIndex == 1) { // 今日
//             $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
//             $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
//         }else if($curHdIndex == 2){ // 昨日
//             $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
//             $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];
//         }else if($curHdIndex == 3){ // 本周
//             $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('this week'))];
//             $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week +6 day'))];
//         }else if($curHdIndex == 4){ // 上周
//             $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
//             $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];
//         }else if($curHdIndex == 5){ // 本月
//             $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
//             $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-0 day"))];
//         }else if($curHdIndex == 6){ // 上月
//             $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
//             $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];
//         }
// //        print_r($where);die;
//         $total_amount = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->sum('total_amount'); // 总金额
//         $ture_amount = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1])->sum('total_amount'); // 实际收款
//         $total_num = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->count('total_amount'); // 总笔数
//         $refund_amount = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [6])->sum('refund_amount'); // 退款金额
//         $refund_num = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [6])->count('refund_amount'); // 退款笔数

//         $obj = Db::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount')->orderBy('created_at', 'desc');
//         $this->t = $obj->count();
//         $store_ids = $this->page($obj)->get();
//         $store_ids = json_decode($store_ids, true);

//         $return = array('order_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'ture_amount' => $ture_amount, 'order_list' => $store_ids);


//         $this->status = 1;
//         $this->message = '数据返回成功';
//         return $this->format($return);
//     }

    /**
     * 查看收银员的收银记录
     * 2022-06-20 16:09
     */
    public function merchant_bill(Request $request){
        $merchant_id = $request->get('merchant_id', ''); // 收银员id
        $curHdIndex = $request->get('curHdIndex'); // 时间
//        print_r($curHdIndex);die;
//        $curHdIndex = 6;
        if ($curHdIndex == 1) { // 今日
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];

            $start_data = date('Y-m-d');
            $end_data = date('Y-m-d');
        }else if($curHdIndex == 2){ // 昨日
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime("-1 day"))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime("-1 day"))];

            $start_data = date('Y-m-d', strtotime("-1 day"));
            $end_data = date('Y-m-d', strtotime("-1 day"));
        }else if($curHdIndex == 3){ // 本周
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('this week'))];
            // $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week +6 day'))];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];
            // $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];

            $start_data = date('Y-m-d', strtotime('this week'));
            // $end_data = date('Y-m-d', strtotime('this week +6 day'));
            $end_data = date('Y-m-d');
            // $end_data = date('Y-m-d');
        }else if($curHdIndex == 4){ // 上周
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('last week'))];
            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime('this week -1 day'))];

            $start_data = date('Y-m-d', strtotime('last week'));
            $end_data = date('Y-m-d', strtotime('this week -1 day'));
        }else if($curHdIndex == 5){ // 本月
            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where[] = ['created_at', '<=', date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), date("t"), date("Y")))];
            // $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];

            $start_data = date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_data = date('Y-m-d', strtotime('-1 day'));
            // $end_data = date('Y-m-d');
        }else if($curHdIndex == 6){ // 上月
//            $where[] = ['created_at', '>=', date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')))];
//            $where[] = ['created_at', '<=', date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400)];

            $start_data = date('Y-m-d' . ' 00:00:00', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00')));
            $end_data = date('Y-m-d' . ' 23:59:59', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400);
        }
        
//        $where[] = ['created_at', '>=', date('Y-04-01') . ' 00:00:00'];
//        $where[] = ['created_at', '<=', date('Y-04-03') . ' 23:59:59'];
//        $start_data = '2022-04-01';
//        $end_data = '2022-04-03';

        // print_r($where);die;

        // 跨天操作
        $time_start_db = date('Ymd', strtotime($start_data));
        $time_end_db = date('Ymd', strtotime($end_data));;
        $is_ct_time = 0;
        if ($time_start_db != $time_end_db) {
            $is_ct_time = 1;
        }
//        print_r( $where );die;
        if( $start_data >= date('Y-m-d', time()) ) { // 今天
            $obj = DB::table('orders');
//            print_r( 2 );die;
            $table = 'orders';
        }else{
            if( $is_ct_time ){
                // print_r( $time_end_db );die;

                // 不含今天
                if( $end_data==date('Y-m-d', time()) ){
                    $time_end_db=$time_end_db - 1; 
                }
                
                $time = $this->getDateFromRanges($time_start_db, $time_end_db);
                // print_r( $time );die;
//                $where[] = [ 'store_id', '=', $store_id ];
                
                // print_r( $time );die;
                foreach( $time as $k => $v ){
                    $where = [];
                    
                    $where[] = ['created_at', '>=', $v.' 00:00:00'];
                    $where[] = ['created_at', '<=', $v.' 23:59:59'];
                    
                    $where[] = [ 'merchant_id', '=', $merchant_id ];
                    // $where[] = [ 'pay_status', ' in ', '(1, 6)' ];

                    $wheres = '';
                    foreach ($where as $key => $val){
    //                        print_r( $v[0] );die;
                        if( $val[0] == 'pay_status' ){
                            if($key == 0){
                                $wheres = $wheres.' where `'.$val[0].'`'.$val[1].$val[2];
                            }else{
                                $wheres = $wheres.' and `'.$val[0].'`'.$val[1].$val[2];
                            }
                        }else{
                            if($key == 0){
                                $wheres = $wheres.' where `'.$val[0].'`'.$val[1]."'".$val[2]."'";
                            }else{
                                $wheres = $wheres.' and `'.$val[0].'`'.$val[1]."'".$val[2]."'";
                            }
                        }
                    }
                    // print_r( $wheres );die;
                    
                    if( $v == date('Y-m-d', time()) ){ // 今天
                        $day_start = 'orders';
                    }else{
                        $day_start = 'orders_' . date( 'Ymd', strtotime($v) );
                    }

                    if($k == 0){
                        $test = '(select * from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 列表数据
                        $count = '(select count(*) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ))'; // 总记录条数(分页)

                        $total_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 总金额
                        $refund_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                        $refund_count = '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                        $get_amount = '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额

                    }else{
                        $test = $test . ' union all ' . '(select * from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 列表数据
                        $count = $count . ' union all ' . '(select count(*) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ))'; // 总记录条数(分页)

                        $total_amount = $total_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and ( `pay_status`=1 or `pay_status`=6 ) )'; // 总金额
                        $refund_amount = $refund_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款金额
                        $refund_count = $refund_count . ' union all ' . '(select count(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=6)'; // 退款笔数
                        $get_amount = $get_amount . ' union all ' . '(select sum(total_amount) from `' . $day_start . '`' . $wheres . ' and `pay_status`=1)'; // 实收金额
//                            print_r( $refund_amount );die;
                    }
                }
//                    print_r( $total_amount );die;
                
                $start = abs((abs(trim($request->get('p', 1))) - 1) * abs(trim($request->get('l', 25))));
                $l = abs( trim($request->get('l', 25)) );
                $test = $test . ' order by `created_at` desc limit ' . $start . "," . $l;
                // print_r( $test );die;
                //->offset($start)->limit($this->l)

                $data = DB::select($test);
                $count = DB::select($count);
                $total_amount = DB::select($total_amount);
                $refund_amount = DB::select($refund_amount);
                $refund_count = DB::select($refund_count);
                $get_amount = DB::select($get_amount);
//                    print_r( $total_amount );die;

                $count = json_decode( json_encode($count, true), true );
                $total_amount = json_decode( json_encode($total_amount, true), true );
                $refund_amount = json_decode( json_encode($refund_amount, true), true );
                $refund_count = json_decode( json_encode($refund_count, true), true );
                $get_amount = json_decode( json_encode($get_amount, true), true );

                    // print_r($total_amount);die;
                $total_num = 0;
                foreach($count as $k => $v){
//                        print_r($v['count(*)']);die;
                    $total_num = $total_num + $v['count(*)'];
                }
//                    print_r($counts);die;

                $total_amounts = 0;
                foreach($total_amount as $k => $v){
                    $total_amounts = $total_amounts + $v['sum(total_amount)'];
                }
                $total_amount = number_format($total_amounts, 2, '.', '');

                $refund_amounts = 0;
                foreach($refund_amount as $k => $v){
                    $refund_amounts = $refund_amounts + $v['sum(total_amount)'];
                }
                $refund_amount = number_format($refund_amounts, 2, '.', '');


                $refund_num = 0;
                foreach($refund_count as $k => $v){
//                        print_r( $v['count(total_amount)'] );die;
                    $refund_num = $refund_num + $v['count(total_amount)'];
                }

//                    print_r( $refund_count );die;
                $get_amounts = 0;
                foreach($get_amount as $k => $v){
                    $get_amounts = $get_amounts + $v['sum(total_amount)'];
                }
//                    print_r( $get_amounts );die;

                $this->status = 1;
                $this->message = '数据返回成功';
                $this->needpage = 1;
                $this->t = $total_num;

                $return = array('order_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'ture_amount' => $total_amount, 'order_list' => $data);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($return);

            }else{
                $day = date('Ymd', strtotime($start_data));
                $table = 'orders_' . $day;

                $obj = DB::table($table);
            }
        }
        
        // 通道扣费模式
        $store_id = DB::table('merchant_stores')->where(['merchant_id' => $merchant_id])->value('store_id');
        $weixin = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', 'weixin')->where('status', 1)->orderBy('sort', 'asc')->value('company'); // 以微信为例, 查当前门店正在用的通道
        if(!empty($weixin)){
            $model = DB::table('company_config')->where('store_id', $store_id)->where(['company' => $weixin])->value('model'); // 查该门店正在用的通道的 通道配置模式
            if($model == 1){
                $model = '服务费模式';
            }else if($model == 2){
                $model = '代扣模式';
            }else if($model == 3){
                $model = '通道扣费';
            }else if($model == 4){
                $model = '预充模式';
            }
        }else{
            $model = '未配置通道扣费模式';
        }
        $rata_money = DB::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->sum('rata_money');
        $fee_amount = DB::table('orders')->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->sum('fee_amount');
        $fee_amount = $fee_amount + $rata_money; // 手续费


        $data = $obj->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->select('ways_source_desc', 'created_at', 'total_amount', 'pay_status_desc', 'store_name', 'ways_source', 'pay_time', 'out_trade_no', 'receipt_amount')->orderBy('created_at', 'desc');
        $this->t = $data->count();
        $store_ids = $this->page($data)->get();
        $store_ids = json_decode($store_ids, true);

        $total_amount = $obj->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->sum('total_amount'); // 总金额
        $ture_amount = $obj->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1])->sum('total_amount'); // 实际收款
        $total_num = DB::table($table)->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [1, 6])->count('total_amount'); // 总笔数
        $refund_amount = DB::table($table)->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [6])->sum('refund_amount'); // 退款金额
        $refund_num = DB::table($table)->where($where)->where('merchant_id', $merchant_id)->whereIn('pay_status', [6])->count('refund_amount'); // 退款笔数

        $return = array('order_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'ture_amount' => $ture_amount, 'order_list' => $store_ids, 'fee_amount' => $fee_amount, 'model' => $model);

        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($return);
    }
    
    // 获取俩时间间隔日期
    public function getDateFromRanges($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);

        $days = ($etimestamp - $stimestamp) / 86400; // 计算日期段内有多少天
//        print_r( $days );die;
        $date = array(); // 保存每天日期

        for($i = 0; $i <= $days; $i++){
            $date[] = date( 'Y-m-d', $stimestamp + (86400 * $i) );
        }
        return $date;
    }
    
    /**
     * 随行付微信认证
     * 2022-07-20 14:38
     */
    function certification(Request $request){
        $store_id = $request->get('store_id', ''); // 门店id
        if(!$store_id) return;
        $contactName = $request->get('contactName', ''); // 联系人姓名
        $phoneNumber = $request->get('phoneNumber', ''); // 联系人手机号
        $contactIdNo = $request->get('contactIdNo', ''); // 联系人身份证号

        $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->get()->toArray();
        if(!$JdStoreItem){
            return json_encode([
                'status' => 2,
                'message' => '随行付mno不存在'
            ]);
        }
//        print_r($JdStoreItem[0]);die;

        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($JdStoreItem[0]->config_id);
//        dump($vbill_config->sxfpublic);die;

        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->wechat_commit_apply;
//        dump($url);die;

//        $JdStoreItem[0]->mno = '399220517423529';
//        $JdStoreItem[0]->applicationId = 'f76c284da5644575aabe94043ccb637d';

        $data = [
            'orgId'     => $vbill_config->orgId,
            'reqId'     => time(),
            'version'   => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType'  => 'RSA',
            'reqData'   => [
//                'applicationId' => $JdStoreItem[0]->applicationId, // f76c284da5644575aabe94043ccb637d
                'mno'   => $JdStoreItem[0]->mno,
                // 'contactName' => '童大伟',
                // 'phoneNumber' => '15601860037',
                // 'contactIdNo' => '342423199007116071',
                
            ],
        ];
        // dump($data);die;
        $res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
        // dump($res);die;
        if( $res['data']['respData']['bizCode'] == '0000' ){
            return json_encode([
                'status' => 1,
                'message' => '操作成功'
            ]);
        }else{
            return json_encode([
                'status' => 2,
                'message' => $res['data']['respData']['bizMsg']
            ]);
        }
        print_r($res);die;
    }
    
    /**
     * 实名认证申请结果查询
     * 2022-07-20 16:12
     */
    function queryApplyInfo(Request $request){
        $store_id = $request->get('store_id', ''); // 门店id
        if(!$store_id) return;
        $contactName = $request->get('contactName', ''); // 联系人姓名
        $phoneNumber = $request->get('phoneNumber', ''); // 联系人手机号
        $contactIdNo = $request->get('contactIdNo', ''); // 联系人身份证号

        $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->get()->toArray();
        if(!$JdStoreItem){
            return json_encode([
                'status' => 2,
                'message' => '随行付未开通，请先开通通道'
            ]);
        }

        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($JdStoreItem[0]->config_id);

        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->queryApplyInfo;

        $data = [
            'orgId'     => $vbill_config->orgId,
            'reqId'     => time(),
            'version'   => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType'  => 'RSA',
            'reqData'   => [
                'mno'   => $JdStoreItem[0]->mno,
            ],
        ];
        $res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
        
        if( empty($res['data']['respData']['infoQrcode']) ){
             return json_encode([
                'status' => 2,
                'message' => $res['data']['respData']['rejectInfo']
            ]);
        }else{
            return json_encode([
                'status' => 1,
                'data' => $res['data']['respData']['infoQrcode'],
                'message' => $res['data']['respData']['infoQrcode']
            ]);
        }
    }
    
    /**
     * 实名认证申请撤销
     * 2022-07-20 17:54
     */
    function backApplyBill(Request $request){
        // print_r(2);die;
$store_id = $request->get('store_id', ''); // 门店id
        if(!$store_id) return;
        $contactName = $request->get('contactName', ''); // 联系人姓名
        $phoneNumber = $request->get('phoneNumber', ''); // 联系人手机号
        $contactIdNo = $request->get('contactIdNo', ''); // 联系人身份证号

        $JdStoreItem = Db::table('vbill_stores')->where(['store_id' => $store_id])->get()->toArray();
        if(!$JdStoreItem){
            return json_encode([
                'status' => 2,
                'message' => '随行付mno不存在'
            ]);
        }
//        print_r($JdStoreItem[0]);die;

        $config = new VbillConfigController();
        $vbill_config = $config->vbill_config($JdStoreItem[0]->config_id);
//        dump($vbill_config->sxfpublic);die;

        $obj = new \App\Api\Controllers\Vbill\BaseController();
        $url = $obj->backApplyBill;
//        dump($url);die;

//        $JdStoreItem[0]->mno = '399220517423529';
//        $JdStoreItem[0]->applicationId = 'f76c284da5644575aabe94043ccb637d';

        $data = [
            'orgId'     => $vbill_config->orgId,
            'reqId'     => time(),
            'version'   => '1.0',
            'timestamp' => date('Ymdhis', time()),
            'signType'  => 'RSA',
            'reqData'   => [
//                'applicationId' => $JdStoreItem[0]->applicationId, // f76c284da5644575aabe94043ccb637d
                'mno'   => $JdStoreItem[0]->mno,
            ],
        ];
        // dump($data);die;
        $res = $obj->execute($data, $url, $vbill_config->privateKey, $vbill_config->sxfpublic);
        // print_r($res);die;
        // return json_encode([
        //     'status' => 1,
        //     'message' => $res['data']['respData']['rejectInfo']
        // ]);
        
        // print_r($res);die;
        if( $res['data']['respData']['bizCode'] == '0000' ){
            return json_encode([
                'status' => 1,
                'message' => $res['data']['respData']['bizMsg']
            ]);
        }else{
            return json_encode([
                'status' => 2,
                'message' => $res['data']['respData']['bizMsg']
            ]);
        }
        
    }
    
    /**
     * 门店流失
     * 2022/09/08 17:00
     */
    function stores_loss(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
//        $num = $request->get('num', ''); // 门店流失天数
        $start_data = $request->get('start_data', ''); //
        $end_data = $request->get('end_data', ''); //
//        print_r( $start_data );die;

        $login_user = DB::table('users')->where('id', $token_user_id)->where('is_delete', '=', '0')->first();
        if (!$login_user) {
            $this->status = '2';
            $this->message = '当前登录状态异常';
            return $this->format();
        }
        $user_ids = $this->getSubIds($token_user_id); // 代理id及下级代理id

        $where = [];
//        if( $num ){
//            $where[] = [ 'num', '=', $num];
//        }
        if( $start_data ){
            $where[] = [ 'start_time', '>=', $start_data];
            $where[] = [ 'start_time', '<=', $end_data];
        }
        if ($start_data != $end_data) {
            $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
            if (!$date) {
                $this->status = '2';
                $this->message = '开始时间不能超过结束时间';
                return $this->format(2);
            }
        }
        //限制时间
        $date = ( strtotime($end_data) - strtotime($start_data) ) / 86400;
        $day = 31;
        if ($date > $day) {
            $this->status = '2';
            $this->message = "时间筛选不能超过 $day 天";
            return $this->format(2);
        }

        $obj = DB::table('stores_loss')->where($where)->whereIn('user_id', $user_ids)->orderby('num', 'desc')->select(); // 门店流失记录
        $this->t = $obj->count();
        $store_ids = $this->page($obj)->get();

        if( $this->t == 0 ){
            $this->status = 1;
            $this->message = '暂无记录';
            return $this->format($store_ids);
        }else{
            foreach($store_ids as $k => $v){
//            print_r( $v );die;
                $data[$k]['store_name'] = DB::table('stores')->where(['store_id' => $v->store_id])->value('store_name');
                $data[$k]['start_time'] = $v->start_time;
                $data[$k]['id'] = $v->store_id;
                $data[$k]['num'] = $v->num;
            }

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        }
    }
    
    /**
     * 配置通道
     * 2022/09/06 14:39
     */
    function configure_channel(Request $request){
        $token = $this->parseToken();
        session_start();
        
        $store_id = $request->get('store_id', '');
        $configure_channel_company = $request->get('configure_channel_company', '');
        
        
        $pash = $request->path();
        $pass = $request->get('pass', '');
        $pass = substr(base64_decode($pass), 0, -5);
        
        $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
        $pass_verify = json_decode($pass_verify, true);
        if( $pass_verify['status'] == '1'){
            $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            $remark = '门店配置通道: 门店id: ' . $store_id . '配置通道：' . $configure_channel_company;
            $this->operation_log($this->parseToken()->user_id, 6, $remark , $pass_id);
        }else{
            return json_encode(['status' => 2, 'message' => '请联系中台给予权限-~', 'data' => []]);
        }
        

        
        $model = $request->get('model', ''); // 选择模式: 1: 服务费模式, 2: 代扣模式, 3: 通道扣费, 4: 预充模式
        $agent_id1 = $request->get('agent_id1'  , '0');
        $agency_cost1 = $request->get('agency_cost1', '0');
        $agent_id2 = $request->get('agent_id2', '0');
        $agency_cost2 = $request->get('agency_cost2', '0');
        $agent_id3 = $request->get('agent_id3', '0');
        $agency_cost3 = $request->get('agency_cost3', '0');
        $agent_id4 = $request->get('agent_id4', '0');
        $agency_cost4 = $request->get('agency_cost4', '0');
        $agent_id5 = $request->get('agent_id5', '0');
        $agency_cost5 = $request->get('agency_cost5', '0');
        $agent_id6 = $request->get('agent_id6', '0');
        $agency_cost6 = $request->get('agency_cost6', '0');
        $agent_id7 = $request->get('agent_id7', '0');
        $agency_cost7 = $request->get('agency_cost7', '0');

        $channel_radio = $request->get('channel_radio', '');
        $configure_channel_fee = $request->get('configure_channel_fee', '');
        $configure_channel_zfb = $request->get('configure_channel_zfb', '');
        $configure_channel_weixin = $request->get('configure_channel_weixin', '');
        $configure_channel_cloud = $request->get('configure_channel_cloud', '');
        $configure_channel_debit = $request->get('configure_channel_debit', '');
        $configure_channel_credit = $request->get('configure_channel_credit', '');

        
        $money_level1 = $request->get('money_level1', '');
        $money_level2 = $request->get('money_level2', '');
        $money_level3 = $request->get('money_level3', '');
        $user_id = DB::table('stores')->where([ 'store_id' => $store_id ])->value('user_id');
        unset($_SESSION['users']);
        $users = $this->recursion1($user_id);
        $users = json_decode($users, true);
        $users = array_reverse($users);
        foreach($users as $k=>$v){
            $rates=DB::table('user_rates')->where([ 'user_id' => $v['id'], 'company' => $configure_channel_company ])->first();
            if($model==1){
                if($configure_channel_fee<$rates->server_rate){
                     return json_encode(['status' => 2, 'message' => '不能低于渠道成本费率', 'data' => []]);
                }
                $users_rate[$k]=array('agent_id'=>$v['id'],'agency_cost'=>$rates->server_rate);
            }else if($model==2){
                if($configure_channel_fee<$rates->era_rate){
                     return json_encode(['status' => 2, 'message' => '不能低于渠道成本费率', 'data' => []]);
                }
                $users_rate[$k]=array('agent_id'=>$v['id'],'agency_cost'=>$rates->era_rate);
            }else if($model==3){
                if($configure_channel_fee<$rates->rate){
                     return json_encode(['status' => 2, 'message' => '不能低于渠道成本费率', 'data' => []]);
                }
                $users_rate[$k]=array('agent_id'=>$v['id'],'agency_cost'=>$rates->rate);
            }else if($model==4){
                if($configure_channel_fee<$rates->yu_rate){
                     return json_encode(['status' => 2, 'message' => '不能低于渠道成本费率', 'data' => []]);
                }
                $users_rate[$k]=array('agent_id'=>$v['id'],'agency_cost'=>$rates->yu_rate);
            }
        }

        if( $channel_radio == 1 ){
            if( $configure_channel_fee == '' ){
                return json_encode([
                    'status' => '2',
                    'message' => '请输入商户扣费费率'
                ]);
            }
            $data = [
                'store_id' => $store_id,
                'model' => $model,
                'company' => $configure_channel_company,
                'users_rate'=>serialize($users_rate),
                'channel_radio' => $channel_radio,
                'configure_channel_fee' => $configure_channel_fee,
                'money_level1'=>$money_level1,
                'money_level2'=>$money_level2,
                'money_level3'=>$money_level3,
                'create_time' => time(),
                'update_time' => time(),
            ];
            
        }else{
            if( $configure_channel_zfb == '' || $configure_channel_weixin == '' || $configure_channel_cloud == '' || $configure_channel_debit == '' || $configure_channel_credit == '' ){
                return json_encode([
                    'status' => '2',
                    'message' => '请填写完整'
                ]);
            }
            $data = [
                'store_id' => $store_id,
                'model' => $model,
                'company' => $configure_channel_company,
                'users_rate'=>serialize($users_rate),
                'channel_radio' => $channel_radio,
                'configure_channel_zfb' => $configure_channel_zfb,
                'configure_channel_weixin' => $configure_channel_weixin,
                'configure_channel_cloud' => $configure_channel_cloud,
                'configure_channel_debit' => $configure_channel_debit,
                'configure_channel_credit' => $configure_channel_credit,
                'money_level1'=>$money_level1,
                'money_level2'=>$money_level2,
                'money_level3'=>$money_level3,
                'create_time' => time(),
                'update_time' => time(),
            ];
        }
        $server_stores=DB::table('server_stores')->where('store_id',$store_id)->first();
        
        $store=DB::table('stores')->where('store_id',$store_id)->first();
        if($model == 4){
            //预充
            DB::table('stores')->where(['store_id' => $store_id])->update(['rata_status' => 1, 'rata_store' => $configure_channel_fee]);
            if(empty($server_stores)){
                DB::table('server_stores')->insert(
                    array(
                        'store_id'=>$store_id,
                        'status'=>0,
                        'rata_store'=>$configure_channel_fee,
                        'store_name'=>$store->store_name,
                        'money_level1'=>$money_level1,
                        'money_level2'=>$money_level2,
                        'money_level3'=>$money_level3,
                        'created_at'=>date('Y-m-d',0),
                        'company'=>$configure_channel_company,
                    )
                );
            }
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update(array('rate'=>0));
            } else {
                foreach ($all_pay_ways as $k=>$v){
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => 0,
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res=DB::table('store_pay_ways')->insert($data1);
                }
            }
        }else if($model == 3){
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update(array('rate'=>$configure_channel_fee));
            } else {
                foreach ($all_pay_ways as $k=>$v){
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res=DB::table('store_pay_ways')->insert($data1);
                }
            }
        }else if($model == 2){
             $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update(array('rate'=>$configure_channel_fee));
            } else {
                foreach ($all_pay_ways as $k=>$v){
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $configure_channel_fee,
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res=DB::table('store_pay_ways')->insert($data1);
                }
            }
        }else if($model == 1){
            
            DB::table('stores')->where(['store_id' => $store_id])->update(['rata_status' => 1, 'rata_store' => $configure_channel_fee]);
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $configure_channel_company)->get();
            $ways = DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->first();
            if ($ways) {
                DB::table('store_pay_ways')->where('store_id', $store_id)->where('company', $configure_channel_company)->update(array('rate'=>0));
            } else {
                foreach ($all_pay_ways as $k=>$v){
                    $gets = DB::table('store_pay_ways')->where('store_id', $store_id)->where('ways_source', $v->ways_source)->get();
                    $count = count($gets);
                    $data1 = [
                        'store_id' => $store_id,
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => 0,
                        'settlement_type' => $v->settlement_type,
                        'status' => 3,
                        'status_desc' => '未开通',
                    ];
                    $res=DB::table('store_pay_ways')->insert($data1);
                }
            }
            
        }

        $configure_channel = DB::table('company_config')->where([ 'store_id' => $store_id, 'company' => $configure_channel_company ])->first(); // 查找记录
        if( $configure_channel ){
            unset($data['create_time']);
            $data['update_time'] = time();
            $res = DB::table('company_config')->where([ 'id' => $configure_channel->id ])->update($data);
        }else{
            $res = DB::table('company_config')->insert($data);
        }


        if($res){
            return json_encode([
                'status' => '1',
                'message' => '配置成功'
            ]);
        }else{
            return json_encode([
                'status' => '2',
                'message' => '网络错误'
            ]);
        }
    }
    
    /**
     * 代理级数
     * 2022/09/06 15:27
     */
    public function agent_level(Request $request){
        session_start();
        $token = $this->parseToken();
        $store_id = $request->get('store_id', ''); // 门店id
        $company = $request->get('company', ''); //
        $model = $request->get('model', ''); //
        $user_id = DB::table('stores')->where([ 'store_id' => $store_id ])->value('user_id'); // 门店的代理id

        unset($_SESSION['users']);
        $users = $this->recursion($user_id,$token->user_id);
        $users = json_decode($users, true);
        $users = array_reverse($users);

        $configure_channel = DB::table('company_config')->where([ 'store_id' => $store_id, 'company' => $company ])->first(); // 查找记录
        
        foreach($users as $k=>$v){
            $rates=DB::table('user_rates')->where([ 'user_id' => $v['id'], 'company' => $company ])->first();
            //通道
            $users_rate[$k]['agent_id']=$v['id'];
            $users_rate[$k]['agency_cost']=$rates->rate;
            //服务费
            $server_rate[$k]['agent_id']=$v['id'];
            $server_rate[$k]['agency_cost']=$rates->server_rate;
            
            //预充
            $yu_rate[$k]['agent_id']=$v['id'];
            $yu_rate[$k]['agency_cost']=$rates->yu_rate;
            
             //代扣
            $era_rate[$k]['agent_id']=$v['id'];
            $era_rate[$k]['agency_cost']=$rates->era_rate;
        }
        
        if( $configure_channel ){
            $configure_channel->users_rate = unserialize($configure_channel->users_rate);
            $configure_channel->daikou=$era_rate;
            $configure_channel->tongdao=$users_rate;
            $configure_channel->fuwufei=$server_rate;
            $configure_channel->yuchong=$yu_rate;
            $data = [
                'users_rate' => $users,
                'configure_channel' => $configure_channel,
            ];
            
            return json_encode([
                'status' => '2',
                'data' => $data
            ]);
        }else{
            $data = [
                'users_rate' => $users,
                'configure_channel' => array('configure_channel_fee'=>'0.00','channel_radio'=>1,'model'=>$model,'money_level1'=>'200','money_level2'=>'100','money_level3'=>'50','users_rate'=>$users_rate,'daikou'=>$era_rate,'fuwufei'=>$server_rate,'tongdao'=>$users_rate,'yuchong'=>$yu_rate),
            ];
            
            return json_encode([
                'status' => '1',
                'data' => $data
            ]);
        }
    }

    /**
     * 递归
     * 2022/09/06 16:07
     */
    public function recursion($user_id, $user_id_ding,$i = 0){
        $user = DB::table('users')->where([ 'id' => $user_id ])->select('id', 'name', 'pid')->get();
        $user = json_decode($user,true);
        if( $user[0]['pid'] !== '0' && $user[0]['id']!=$user_id_ding){
            $_SESSION['users'][$i] = $user[0];
            $i++;
            $this->recursion($user[0]['pid'],$user_id_ding,$i);
        }else{
            $_SESSION['users'][$i] = $user[0];
        }
        return json_encode((object)$_SESSION['users']);
    }
    
    /**
     * 递归
     * 2022/09/06 16:07
     */
    public function recursion1($user_id,$i = 0){
        $user = DB::table('users')->where([ 'id' => $user_id ])->select('id', 'name', 'pid')->get();
        $user = json_decode($user,true);
        if( $user[0]['pid'] !== '0'){
            $_SESSION['users'][$i] = $user[0];
            $i++;
            $this->recursion1($user[0]['pid'],$i);
        }else{
            $_SESSION['users'][$i] = $user[0];
        }
        return json_encode((object)$_SESSION['users']);
    }

    public function view_branch(Request $request)
    {
        $merchant = $this->parseToken();
        $curHdIndex = $request->get('curHdIndex', '');
        $curtypeIndex = $request->get('curtypeIndex', '');
        $storeId = $request->get('store_id', false);
        $store_ids = MerchantStore::where(function ($query) use (&$merchant, $storeId) {
            $query->where('merchant_id', $merchant->merchant_id);
            if ($storeId > 0) {
                $query->where('store_id', $storeId);
            }
            return $query;
        })->pluck('store_id')->toArray();
        
        
        
        
        
        
        switch (intval($curHdIndex)) {
            case 2://昨日
                $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                break;
            case 3://本周
                $date_start = date('Y-m-d 00:00:00', strtotime('this week monday'));
                $date_end = date('Y-m-d 23:59:59', strtotime('this week sunday'));
                break;
            case 4://上周
                $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                break;
            case 5://本月
                $date_start = date('Y-m-01 00:00:00');
                $date_end = date('Y-m-t 23:59:59');
                break;
            case 6://上月
                $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                break;
            default:
                $date_start = date('Y-m-d 00:00:00');
                $date_end = date('Y-m-d 23:59:59');
        }
        switch (intval($curtypeIndex)) {
            //支付类型
            case 2:
                $select = [
                    'receive_code',
                    DB::raw('sum(receive_fee) as receive_fee'),
                    DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                    DB::raw('sum(order_total) as order_total'),
                    DB::raw('sum(order_amount) as order_amount'),
                    DB::raw('sum(refund_total) as refund_total'),
                    DB::raw('sum(refund_amount) as refund_amount'),
                ];
                $group = Db::raw('receive_code');
                break;
            //日期
            case 3:
                $select = [
                    DB::raw('FROM_UNIXTIME(bill_date, "%Y-%m-%d") as bill_date'),
                    DB::raw('sum(receive_fee) as receive_fee'),
                    DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                    DB::raw('sum(order_total) as order_total'),
                    DB::raw('sum(order_amount) as order_amount'),
                    DB::raw('sum(refund_total) as refund_total'),
                    DB::raw('sum(refund_amount) as refund_amount'),
                ];
                $group = Db::raw('FROM_UNIXTIME(bill_date, "%Y-%m-%d")');
                break;
            default:
                $select = [
                    'shop_id',
                    DB::raw('sum(receive_fee) as receive_fee'),
                    DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                    DB::raw('sum(order_total) as order_total'),
                    DB::raw('sum(order_amount) as order_amount'),
                    DB::raw('sum(refund_total) as refund_total'),
                    DB::raw('sum(refund_amount) as refund_amount'),
                ];
                $group = Db::raw('shop_id');
        }
        $return = [
            'total_num' => 0,
            'refund_num' => 0,
            'total_amount' => 0.00,
            'refund_amount' => 0.00,
            'real_amount' => 0.00,
            'fee_amount' => 0.00,
            'final_amount' => 0.00,
            'merchant_list' => []
        ];
        try {
            if (!is_array($store_ids) || count($store_ids) == 0) {
                throw new \Exception("商户不存在");
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end < $date_start) {
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start < strtotime('2023-06-01')) {
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end > strtotime(date('Y-m-t 23:59:59'))) {
                throw new \Exception("查询最大时间不能高于当月");
            }
            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
            $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
            $pluck = DB::connection('old_mysql')->table($tableName)
                ->whereIn('shop_id', $store_ids)
                ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                ->select($select)
                ->groupBy($group);
            for ($i = 0; $i < $monthTotal; $i++) {
                $num = $i + 1;
                $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                $union_pluck = DB::connection('old_mysql')->table($tableName)
                    ->whereIn('shop_id', $store_ids)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select($select)
                    ->groupBy($group);
                $pluck->unionAll($union_pluck);
            }
            foreach ($pluck->get() as $obj) {
                $item = (array)$obj;
                $shopId = $item['shop_id'] ?? '';
                $order_amount = isset($item['order_amount']) ? bcdiv($item['order_amount'], 100, 2) : 0.00;
                $refund_amount = isset($item['refund_amount']) ? bcdiv($item['refund_amount'], 100, 2) : 0.00;
                $fee_amount = bcdiv(bcsub($item['receive_fee'], $item['receive_refund_fee']), 100, 2);
                $real_amount = bcsub($order_amount, $refund_amount, 2);
                $final_amount = bcsub($real_amount, $fee_amount, 2);

                $return['total_amount'] = bcadd($return['total_amount'], $order_amount, 2);
                $return['refund_amount'] = bcadd($return['refund_amount'], $refund_amount, 2);

                $return['total_num'] = bcadd($return['total_num'], $item['order_total']);
                $return['refund_num'] = bcadd($return['refund_num'], $item['refund_total']);

                $return['fee_amount'] = bcadd($return['fee_amount'], $fee_amount, 2);

                $return['real_amount'] = bcadd($return['real_amount'], $real_amount, 2);
                $return['final_amount'] = bcadd($return['final_amount'], $final_amount, 2);


                if ($curtypeIndex == 2) {//支付类型
                    $ways_desc = Db::table('store_ways_desc')->where('ways_type', $item['receive_code'])->value('ways_desc');
                    if ($ways_desc) {
                        $explode = explode( '-',$ways_desc);
                        $_index = array_search($explode[0], array_column($return['merchant_list'], 'merchant_name'));
                        if ($_index !== false) {
                            $return['merchant_list'][$_index]['merchant_total'] = bcadd($return['merchant_list'][$_index]['merchant_total'], $item['order_total']);
                            $return['merchant_list'][$_index]['merchant_amount'] = bcadd($return['merchant_list'][$_index]['merchant_amount'], $order_amount, 2);
                            $return['merchant_list'][$_index]['merchant_num'] = '交易笔数： ' . $return['merchant_list'][$_index]['merchant_total'] . '笔';
                        } else {
                            $return['merchant_list'][] = [
                                'merchant_total' => $item['order_total'],
                                'merchant_amount' => $order_amount,
                                'merchant_name' => $explode[0],
                                'merchant_num' => '交易笔数： ' . ($item['order_total'] ?? 0) . '笔',
                                'money_name' => '入账金额',
                                'store_name' => '交易类型',
                                'store_id' => $shopId,
                            ];
                        }
                    }
                } else if ($curtypeIndex == 3) {//日期
                    $return['merchant_list'][] = [
                        'merchant_amount' => $order_amount,
                        'merchant_name' => $item['bill_date'],
                        'merchant_num' => '交易笔数： ' . ($item['order_total'] ?? 0) . '笔',
                        'money_name' => '入账金额',
                        'store_name' => '交易日期',
                        'store_id' => $shopId,
                    ];
                } else {
                    $shopName = '';
                    if ($shopId > 0) {
                        $shopName = Db::table('stores')->where('store_id', $shopId)->value('store_name');
                    }
                    $return['merchant_list'][] = [
                        'merchant_amount' => $order_amount,
                        'merchant_name' => $shopName,
                        'merchant_num' => '交易笔数： ' . ($item['order_total'] ?? 0) . '笔',
                        'money_name' => '入账金额',
                        'store_name' => '',
                        'store_id' => $shopId,
                    ];
                }
            }
            if (!in_array(intval($curHdIndex), [2, 3, 4, 5, 6]) && $return['refund_num'] == 0) {
                $refundResult = DB::table('orders')
                    ->whereIn('store_id', $store_ids)
                    ->whereBetween('created_at',[$date_start,$date_end])
                    ->where('pay_status', 6)
                    ->select([
                        Db::raw('count(out_trade_no) as refund_num'),
                        Db::raw('sum(refund_amount) as refund_amount'),
                        Db::raw('sum(refund_amount*(rate/100)) as refund_fee'),
                    ])->first();
                if ($refundResult && $refundResult->refund_num>0) {
                    $refundResult->refund_fee = bcdiv(bcmul($refundResult->refund_fee,100),100,2);
                    $return['refund_num'] = $refundResult->refund_num;
                    $return['refund_amount'] = $refundResult->refund_amount;

                    $return['fee_amount'] = bcsub($return['fee_amount'], $refundResult->refund_fee, 2);
                    $return['real_amount'] = bcsub($return['real_amount'], $return['refund_amount'], 2);
                    $return['final_amount'] = bcsub($return['real_amount'], $return['fee_amount'], 2);
                }
            }
            $this->status = 0;
            return $this->format($return);
        } catch (\Exception $e) {
            $this->status = 1;
            $this->message = $e->getMessage();
            return $this->format($return);
        }
    }

    /**
     * 查看分店
     * 2022-09-19 10:49
     */
    public function _view_branch(Request $request){
        $merchant = $this->parseToken();
        $currentTable = 'wft_stores_orders_'.date('Ym').'_bill';
        $lastTable = 'wft_stores_orders_'.date('Ym',strtotime("last month")).'_bill';
        $curHdIndex = $request->get('curHdIndex', '');
        $curtypeIndex = $request->get('curtypeIndex', '');
        $MerchantStore = MerchantStore::where('merchant_id', $merchant->merchant_id)->select('store_id')->limit(10)->get(); // 门店列表 二维
        $store_ids = $MerchantStore->toArray();
        $store_f= DB::table('stores')->where('store_id',$store_ids[0]['store_id'])->select('*')->first();
        if($curHdIndex == 1){ // 今日
            $where[] = ['orders.created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['orders.created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            $id=$store_f->id;
            $order_data = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [1, 6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total'),DB::raw('sum(orders.fee_amount) as fee_amount')])->first();
            $order_data_ref = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('sum(orders.refund_amount) as refund_amount'),DB::raw('count(orders.out_trade_no) as total')])->first();
            
            $total_amount = $order_data->total_amount?$order_data->total_amount:0.00; // 总收款
            $fee_amount = $order_data->total_amount?$order_data->fee_amount:0.00; // 总手续费
            $refund_amount = $order_data_ref->refund_amount?$order_data_ref->refund_amount:0.00;  // 总退款
            $total_num = $order_data->total; // 总收款笔数
            $refund_num = $order_data_ref->total; // 总退款笔数
            $final_amount = bcsub($total_amount, $fee_amount + $refund_amount, 2);
            $real_amount = bcsub($total_amount, $refund_amount, 2);
            $data = array();
            if($curtypeIndex==1){
                foreach($store_ids as $key => $val){
                    $store = DB::table('stores')->where('store_id', $val)->select('rata_status', 'store_name', 'store_id')->first();
                    if(empty($store)){
                        $data[$key]['store_id'] = '门店已清除';
                        $data[$key]['merchant_name'] = '门店已清除';
                    }else{
                        $data[$key]['store_id'] = $store->store_id;
                        $data[$key]['merchant_name'] = $store->store_name;
                    }
                    // $data[$key]['store_name'] = DB::table('stores')->where('store_id', $val)->value('store_name');
                    $data[$key]['merchant_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1, 6])->select()->sum('total_amount'); // 门店总金额
                    $data[$key]['total_num'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1, 6])->select()->count('total_amount'); // 门店总笔数
                    $data[$key]['refund_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [6])->select()->sum('total_amount'); // 门店退款金额
                    // if( $store->rata_status > 0 ){
                        $data[$key]['rata_money'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1])->select()->sum('rata_money');
                    // }else{
                        $data[$key]['fee_amount'] = DB::table('orders')->where('store_id', $val)->where($where)->whereIn('pay_status', [1])->select()->sum('fee_amount');
                        $data[$key]['fee_amount'] = $data[$key]['fee_amount'] + $data[$key]['rata_money'];
                    // }
                    $data[$key]['commission_money'] = '未结算';
                    $data[$key]['money_name']='入账金额';
                    $data[$key]['merchant_num']='交易笔数：'.$data[$key]['total_num'].'笔';
                }
                array_multisort( array_column($data, 'merchant_amount'), SORT_DESC, $data );
                // dump($data);die;
                $return = array('total_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($return);
            }
            if($curtypeIndex==2){
                $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay');
                foreach($ways_source as $k=>$v){
                    if($v=='weixin'){
                        $way_type='微信支付';
                    }else if($v=='alipay'){
                        $way_type='支付宝支付';
                    }else if($v=='unionpay'){
                        $way_type='云闪付支付';
                    }else if($v=='Bestpay'){
                        $way_type='翼支付支付';
                    }
                    $stores_data_way= DB::table('orders')->join('stores', function ($join) {
                    $join->on('orders.store_id', '=', 'stores.store_id');
                })
                    ->where('orders.ways_source', $v)
                    ->whereIn('orders.pay_status', [1,6])
                    ->where($where)
                    ->where(function ($query) use($id) {
                        $query->where('stores.id', $id)->orwhere('stores.pid',$id);
                        return $query;
                    })
                    ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
                    ->first();
                    $ways_amount=$stores_data_way->total_amount?$stores_data_way->total_amount:0.00;
                    $ways_sum=$stores_data_way->total;
                    $merchant_item[$k]['store_name']='交易类型';
                    $merchant_item[$k]['merchant_name']=$way_type;
                    $merchant_item[$k]['merchant_num']='交易笔数：'.$ways_sum.'笔';
                    $merchant_item[$k]['money_name']='入账金额';
                    $merchant_item[$k]['merchant_amount']=$ways_amount;
                }
                $return=array('total_num'=>$total_num,'total_amount'=>$total_amount,'refund_num'=>$refund_num,'refund_amount'=>$refund_amount,'real_amount'=>$total_amount-$refund_amount,'fee_amount'=>$fee_amount,'final_amount'=>$final_amount,'merchant_list'=>$merchant_item);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($return);
            }
            if($curtypeIndex==3){
                $merchant_item[0]['store_name']='交易日期';
                $merchant_item[0]['merchant_name']=date('Y-m-d');
                $merchant_item[0]['merchant_num']='交易笔数：'.$total_num.'笔';
                $merchant_item[0]['money_name']='入账金额';
                $merchant_item[0]['merchant_amount']=$total_amount;
                $return=array('total_num'=>$total_num,'total_amount'=>$total_amount,'refund_num'=>$refund_num,'refund_amount'=>$refund_amount,'real_amount'=>$total_amount-$refund_amount,'fee_amount'=>$fee_amount,'final_amount'=>$final_amount,'merchant_list'=>$merchant_item);
                $this->status = 1;
                $this->message = '数据返回成功';
                return $this->format($return);
            }
        }
        if($curHdIndex == 2){ // 昨日
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
        }else if($curHdIndex == 3){ // 本周
            $time=date('d')-1;
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y')))];
        }else if($curHdIndex == 4){ // 上周
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-14,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-14,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
        }else if($curHdIndex == 5){ // 本月
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime("-1 day"))];
        }else if($curHdIndex == 6){ // 上月
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
        }

        $store_amount =DB::connection('old_mysql')->table($currentTable)->whereIn('shop_id', $store_ids)->where($where)->select('order_amount')->sum('order_amount')/100;
        $total_num = DB::connection('old_mysql')->table($currentTable)->whereIn('shop_id', $store_ids)->where($where)->select('order_total')->sum('order_total');
        $refund_amount = DB::connection('old_mysql')->table($currentTable)->whereIn('shop_id', $store_ids)->where($where)->select('refund_amount')->sum('refund_amount')/100;
        $refund_num = DB::connection('old_mysql')->table($currentTable)->whereIn('shop_id', $store_ids)->where($where)->select('refund_total')->sum('refund_total');
        $fee_amount = DB::connection('old_mysql')->table($currentTable)->whereIn('shop_id', $store_ids)->where($where)->select('receive_fee')->sum('receive_fee')/100;
        
        $store_amount1 =DB::connection('old_mysql')->table($lastTable)->whereIn('shop_id', $store_ids)->where($where)->select('order_amount')->sum('order_amount')/100;
        $total_num1 = DB::connection('old_mysql')->table($lastTable)->whereIn('shop_id', $store_ids)->where($where)->select('order_total')->sum('order_total');
        $refund_amount1 = DB::connection('old_mysql')->table($lastTable)->whereIn('shop_id', $store_ids)->where($where)->select('refund_amount')->sum('refund_amount')/100;
        $refund_num1 = DB::connection('old_mysql')->table($lastTable)->whereIn('shop_id', $store_ids)->where($where)->select('refund_total')->sum('refund_total');
        $fee_amount1 = DB::connection('old_mysql')->table($lastTable)->whereIn('shop_id', $store_ids)->where($where)->select('receive_fee')->sum('receive_fee')/100;
        $store_amount=$store_amount+$store_amount1;
        $total_num=$total_num+$total_num1;
        $refund_amount=$refund_amount1+$refund_amount;
        $refund_num=$refund_num1+$refund_num;
        $fee_amount=$fee_amount+$fee_amount1;
        $store123=DB::table('stores')->where('rata_status','1')->where('store_id',$store_ids[0]['store_id'])->where('pid','4377')->first();
        if(!empty($store123)){
           $fee_amount = '0.00';
        }
        $final_amount = bcsub($store_amount, $fee_amount + $refund_amount, 2);
        $real_amount = bcsub($store_amount, $refund_amount, 2);
        if($curtypeIndex==1){
            $_refund_amount = 0;
            foreach($store_ids as $key => $val){
                $store = DB::table('stores')->where('store_id', $val)->select('rata_status', 'store_name', 'store_id')->first();
                if(empty($store)){
                    $data[$key]['store_id'] = '门店已清除';
                    $data[$key]['merchant_name'] = '门店已清除';
                }else{
                    $data[$key]['store_id'] = $store->store_id;
                    $data[$key]['merchant_name'] = $store->store_name;
                }
                
                $merchant_amount=DB::connection('old_mysql')->table($currentTable)->where('shop_id', $val)->where($where)->select('order_amount')->sum('order_amount')/100;
                $merchant_amount1=DB::connection('old_mysql')->table($lastTable)->where('shop_id', $val)->where($where)->select('order_amount')->sum('order_amount')/100;
                $data[$key]['merchant_amount']=$merchant_amount+$merchant_amount1;
                $order_total=DB::connection('old_mysql')->table($currentTable)->where('shop_id', $val)->where($where)->select('order_total')->sum('order_total');
                $order_total1=DB::connection('old_mysql')->table($lastTable)->where('shop_id', $val)->where($where)->select('order_total')->sum('order_total');
                $data[$key]['total_num']=$order_total1+$order_total;
                
                $refund_amount=DB::connection('old_mysql')->table($currentTable)->where('shop_id', $val)->where($where)->select('refund_amount')->sum('refund_amount')/100;
                $refund_amount1=DB::connection('old_mysql')->table($lastTable)->where('shop_id', $val)->where($where)->select('refund_amount')->sum('refund_amount')/100;
                $data[$key]['refund_amount']=$refund_amount1+$refund_amount;
                $_refund_amount += $refund_amount;
                
                $receive_fee=DB::connection('old_mysql')->table($currentTable)->where('shop_id', $val)->where($where)->select('receive_fee')->sum('receive_fee')/100;
                $receive_fee1=DB::connection('old_mysql')->table($lastTable)->where('shop_id', $val)->where($where)->select('receive_fee')->sum('receive_fee')/100;
                $data[$key]['fee_amount']=$receive_fee1+$receive_fee;
                
                $data[$key]['commission_money'] = 0.00; // 佣金
                $data[$key]['money_name']='入账金额';
                $data[$key]['merchant_num']='交易笔数：'.$data[$key]['total_num'].'笔';
            }
            
            array_multisort( array_column($data, 'merchant_amount'), SORT_DESC, $data );
    
            $return = array('total_num' => $total_num, 'total_amount' => $store_amount, 'refund_num' => $refund_num, 'refund_amount' => $_refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
        if($curtypeIndex==2){
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay');
            foreach($ways_source as $k=>$v){
                // $id=$store_f->id;
                // $ways=DB::table('store_pay_ways')->join('stores', function ($join) {
                //     $join->on('store_pay_ways.store_id', '=', 'stores.store_id');
                // })
                // ->where('store_pay_ways.ways_source', $v)
                // ->where(function ($query) use($id) {
                //     $query->where('stores.id', $id)->orwhereIn('stores.pid',$id);
                //     return $query;
                // })
                // ->select('ways_type as receive_code')
                // ->distinct()
                // ->get();
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')
                ->distinct()
                ->get();
                $ways=json_decode($ways,true);

                if($v=='weixin'){
                    $way_type='微信支付';
                    $ways_amount=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum=DB::connection('old_mysql')->table($lastTable)->where($where)->where('store_id', $store_ids[0]['store_id'])->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='alipay'){
                    $way_type='支付宝支付';
                   $ways_amount=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum=DB::connection('old_mysql')->table($lastTable)->where($where)->where('store_id', $store_ids[0]['store_id'])->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='unionpay'){
                    $way_type='云闪付支付';
                    $ways_amount=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum=DB::connection('old_mysql')->table($lastTable)->where($where)->where('store_id', $store_ids[0]['store_id'])->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='Bestpay'){
                    $way_type='翼支付支付';
                    $ways_amount=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum=DB::connection('old_mysql')->table($lastTable)->where($where)->where('store_id', $store_ids[0]['store_id'])->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }
                if($v=='weixin'){
                    $way_type='微信支付';
                    $ways_amount1=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum1=DB::connection('old_mysql')->table($lastTable)->where($where)->where('store_id', $store_ids[0]['store_id'])->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='alipay'){
                    $way_type='支付宝支付';
                   $ways_amount1=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum1=DB::connection('old_mysql')->table($lastTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='unionpay'){
                    $way_type='云闪付支付';
                    $ways_amount1=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum1=DB::connection('old_mysql')->table($lastTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }else if($v=='Bestpay'){
                    $way_type='翼支付支付';
                    $ways_amount1=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $ways_sum1=DB::connection('old_mysql')->table($lastTable)->where($where)->whereIn('shop_id', $store_ids)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                }
                $ways_amount=$ways_amount1+$ways_amount;
                $ways_sum1=$ways_sum+$ways_sum1;
                $merchant_item[$k]['store_name']='交易类型';
                $merchant_item[$k]['merchant_name']=$way_type;
                $merchant_item[$k]['merchant_num']='交易笔数：'.$ways_sum.'笔';
                $merchant_item[$k]['money_name']='入账金额';
                $merchant_item[$k]['merchant_amount']=$ways_amount;
            }
            $return=array('total_num'=>$total_num,'total_amount'=>$store_amount,'refund_num'=>$refund_num,'refund_amount'=>$refund_amount,'real_amount'=>$store_amount-$refund_amount,'fee_amount'=>$fee_amount,'final_amount'=>$final_amount,'merchant_list'=>$merchant_item);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
        if($curtypeIndex==3){
            if($curHdIndex==2){
                $date=$this->getDateFromRanges(date('Y-m-d',strtotime("-1 day")),date('Y-m-d',strtotime("-1 day")));
            }else if($curHdIndex==3){
                $date=$this->getDateFromRanges(date('Y-m-d', strtotime("this week")),date('Y-m-d',strtotime("-1 day")));
            }else if($curHdIndex==4){
                $date=$this->getDateFromRanges(date('Y-m-d', strtotime('last week')),date('Y-m-d', strtotime('this week -1 day')));
            }else if($curHdIndex==5){
                $date=$this->getDateFromRanges(date('Y-m-d', strtotime(date('Y-m', time()).'-01 00:00:00')),date('Y-m-d',strtotime("-1 day")));
            }else if($curHdIndex==6){
                $date=$this->getDateFromRanges(date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))),date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400));
            }
            foreach($date as $k=>$v){
                $s_time=strtotime($v.' 00:00:00');
                $e_time=strtotime($v.' 23:59:59');
                $data_amount=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->where('bill_date','>=',$s_time)->where('bill_date','<=',$s_time)->select('order_amount')->sum('order_amount')/100;
                $data_num=DB::connection('old_mysql')->table($currentTable)->where($where)->whereIn('shop_id', $store_ids)->where('bill_date','>=',$s_time)->where('bill_date','<=',$s_time)->select('order_total')->sum('order_total');
                
                $data_amount1=DB::connection('old_mysql')->table($lastTable)->where($where)->whereIn('shop_id', $store_ids)->where('bill_date','>=',$s_time)->where('bill_date','<=',$s_time)->select('order_amount')->sum('order_amount')/100;
                $data_num1=DB::connection('old_mysql')->table($lastTable)->where($where)->whereIn('shop_id', $store_ids)->where('bill_date','>=',$s_time)->where('bill_date','<=',$s_time)->select('order_total')->sum('order_total');
                $data_amount=$data_amount+$data_amount1;
                $data_num=$data_num1+$data_num;
                
                $merchant_item[$k]['store_name']='交易日期';
                $merchant_item[$k]['merchant_name']=$v;
                $merchant_item[$k]['merchant_num']='交易笔数：'.$data_num.'笔';
                $merchant_item[$k]['money_name']='入账金额';
                $merchant_item[$k]['merchant_amount']=$data_amount;
            }
            $return=array('total_num'=>$total_num,'total_amount'=>$store_amount,'refund_num'=>$refund_num,'refund_amount'=>$refund_amount,'real_amount'=>$store_amount-$refund_amount,'fee_amount'=>$fee_amount,'final_amount'=>$final_amount,'merchant_list'=>$merchant_item);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
    }
    
    public function view_merchant(Request $request){
        $merchant = $this->parseToken();
        $curHdIndex = $request->get('curHdIndex', '');
        $storeId = $request->get('store_id', false);
        $storeName = DB::table('merchant_stores')->join('stores','merchant_stores.store_id','=','stores.store_id','INNER')
            ->where([
                'merchant_stores.merchant_id'=>$merchant->merchant_id,
                'merchant_stores.store_id'=>$storeId,
            ])->value('store_name');
        switch (intval($curHdIndex)) {
            case 2://昨日
                $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                break;
            case 3://本周
                $date_start = date('Y-m-d 00:00:00', strtotime('this week monday'));
                $date_end = date('Y-m-d 23:59:59', strtotime('this week sunday'));
                break;
            case 4://上周
                $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                break;
            case 5://本月
                $date_start = date('Y-m-01 00:00:00');
                $date_end = date('Y-m-t 23:59:59');
                break;
            case 6://上月
                $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                break;
            default:
                $date_start = date('Y-m-d 00:00:00');
                $date_end = date('Y-m-d 23:59:59');
        }

        $return = [
            'total_num' => 0,
            'refund_num' => 0,
            'total_amount' => 0.00,
            'refund_amount' => 0.00,
            'real_amount' => 0.00,
            'fee_amount' => 0.00,
            'final_amount' => 0.00,
            'merchant_list' => []
        ];
        try {
            if (!$storeName) {
                throw new \Exception("商户不存在");
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end < $date_start) {
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start < strtotime('2023-06-01')) {
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end > strtotime(date('Y-m-t 23:59:59'))) {
                throw new \Exception("查询最大时间不能高于当月");
            }

            $select = [
                'merchant_id',
                DB::raw('sum(receive_fee) as receive_fee'),
                DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                DB::raw('sum(order_total) as order_total'),
                DB::raw('sum(order_amount) as order_amount'),
                DB::raw('sum(refund_total) as refund_total'),
                DB::raw('sum(refund_amount) as refund_amount'),
            ];
            $group = Db::raw('merchant_id');

            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));
            $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
            $pluck = DB::connection('old_mysql')->table($tableName)
                ->where('shop_id', $storeId)
                ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                ->select($select)
                ->groupBy($group);
            for ($i = 0; $i < $monthTotal; $i++) {
                $num = $i + 1;
                $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                $union_pluck = DB::connection('old_mysql')->table($tableName)
                    ->whereIn('shop_id', $storeId)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select($select)
                    ->groupBy($group);
                $pluck->unionAll($union_pluck);
            }
            foreach ($pluck->get() as $obj) {
                $item = (array)$obj;
                $merchantName = DB::table('merchants')->where('id',$item['merchant_id'])->value('name');
                $order_amount = isset($item['order_amount']) ? bcdiv($item['order_amount'], 100, 2) : 0.00;
                $refund_amount = isset($item['refund_amount']) ? bcdiv($item['refund_amount'], 100, 2) : 0.00;
                $fee_amount = bcdiv(bcsub($item['receive_fee'], $item['receive_refund_fee']), 100, 2);
                $real_amount = bcsub($order_amount, $refund_amount, 2);
                $final_amount = bcsub($real_amount, $fee_amount, 2);

                $return['total_amount'] = bcadd($return['total_amount'], $order_amount, 2);
                $return['refund_amount'] = bcadd($return['refund_amount'], $refund_amount, 2);

                $return['total_num'] = bcadd($return['total_num'], $item['order_total']);
                $return['refund_num'] = bcadd($return['refund_num'], $item['refund_total']);

                $return['fee_amount'] = bcadd($return['fee_amount'], $fee_amount, 2);

                $return['real_amount'] = bcadd($return['real_amount'], $real_amount, 2);
                $return['final_amount'] = bcadd($return['final_amount'], $final_amount, 2);


                $return['merchant_list'][] = [
                    'merchant_id' => $item['merchant_id'],
                    'merchant_amount' => $order_amount,
                    'merchant_name' => $merchantName ?? '',
                    'merchant_num' => '交易笔数： ' . ($item['order_total'] ?? 0) . '笔',
                    'money_name' => '入账金额',
                    'store_name' => $storeName,
                    'store_id' => $storeId,
                ];
            }
            $this->status = 0;
            return $this->format($return);
        } catch (\Exception $e) {
            $this->status = 1;
            $this->message = $e->getMessage();
            return $this->format($return);
        }
    }
    
    /**
     * 查看收银员
     * 2022-09-19 14:43
     */
    public function _view_merchant(Request $request){
        $curHdIndex = $request->get('curHdIndex', '');
        $store_id = $request->get('store_id', '');
        
        $store_ids[] = $request->get('store_id', '');
        
        $cashier = Db::table('merchant_stores')->where('merchant_id', '>', 0)->whereIn('store_id', $store_ids)->select('merchant_id', 'store_id')->get();
        $cashier = json_decode($cashier, true);
        if($curHdIndex == 1){
            $where[] = ['created_at', '>=', date('Y-m-d') . ' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d') . ' 23:59:59'];

            $total_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount'); // 总收款
            $fee_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('fee_amount')->sum('fee_amount'); // 总手续费
            $refund_amount = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->sum('refund_amount'); // 总退款
            $total_num = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->count(); // 总收款笔数
            $refund_num = Order::whereIn('store_id', $store_ids)->where($where)->whereIn('pay_status', [6])->select('refund_amount')->count(); // 总退款笔数
            $final_amount = bcsub($total_amount, $fee_amount + $refund_amount, 2);
            $real_amount = bcsub($total_amount, $refund_amount, 2);
            $data = array();
            // print_r( $cashier );die;
            foreach($cashier as $key => $val){
                $cashier_data = DB::table('merchants')->where('id', $val['merchant_id'])->select('name')->first();
                $store = DB::table('stores')->where('store_id', $val['store_id'])->select('store_name','pid')->first();
                $data[$key]['merchant_id'] = $val['merchant_id'];
                $data[$key]['store_name'] = $store->store_name;
                $data[$key]['merchant_name'] = $cashier_data->name;
                // print_r( $val['store_id'] );die;
                $data[$key]['merchant_amount'] = DB::table('orders')->where('merchant_id', $val['merchant_id'])->where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select()->sum('total_amount'); // 门店总金额
                $data[$key]['total_num'] = DB::table('orders')->where('merchant_id', $val['merchant_id'])->where('store_id', $val['store_id'])->where($where)->whereIn('pay_status', [1, 6])->select()->count('total_amount'); // 门店总笔数
                if($store->pid == 0 ){
                    $data[$key]['store_name'] = '总店：' . $store->store_name;
                }else{
                    $data[$key]['store_name'] = '分店：' . $store->store_name;
                }
                $data[$key]['merchant_num'] = '交易笔数：' . $data[$key]['total_num'] . '笔';
                $data[$key]['money_name'] = '入账金额';
                $data[$key]['store_id'] = $val['store_id'];
            }
            array_multisort( array_column($data, 'merchant_amount'), SORT_DESC, $data );
            // dump($data);die;
            $return = array('total_num' => $total_num, 'total_amount' => $total_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data);
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($return);
        }
        if($curHdIndex == 2){ // 昨日
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
        }else if($curHdIndex == 3){ // 本周
            $time=date('d')-1;
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
        }else if($curHdIndex == 4){ // 上周
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
        }else if($curHdIndex == 5){ // 本月
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d',strtotime("-1 day"));
        }else if($curHdIndex == 6){ // 上月
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime('-1 month')))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $start_date=date('Y-m-01',strtotime('-1 month'));
            $end_date=date("Y-m-d", strtotime(-date('d').'day'));
        }
        
         //总收款
        if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
            $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['order_amount']);
            $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['order_amount']);
            $ways_amount->unionAll($ways_amount1);
            $store_amount=0;
            foreach ($ways_amount->get() as $obj) {
                $store_amount += $obj->order_amount;
            }
            $store_amount=$store_amount/100;
            
            $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['refund_amount']);
            $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['refund_amount']);
            $refund_amount_zong->unionAll($refund_amount1);
            $refund_amount=0;
            foreach ($refund_amount_zong->get() as $obj) {
                $refund_amount += $obj->refund_amount;
            }
            $refund_amount=$refund_amount/100;
            
            $fee_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['receive_fee']);
            $fee_amount_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['receive_fee']);
            $fee_amount_zong->unionAll($fee_amount_zong1);
            $fee_amount=0;
            foreach ($fee_amount_zong->get() as $obj) {
                $fee_amount += $obj->receive_fee;
            }
            $fee_amount=$fee_amount/100;
            
            $total_num_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['order_total']);
            $total_num_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['order_total']);
            $total_num_zong->unionAll($total_num_zong1);
            $total_num=0;
            foreach ($total_num_zong->get() as $obj) {
                $total_num += $obj->order_total;
            }
            
            $refund_num_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['refund_total']);
            $refund_num_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['refund_total']);
            $refund_num_zong->unionAll($refund_num_zong1);
            $refund_num=0;
            foreach ($refund_num_zong->get() as $obj) {
                $refund_num += $obj->refund_total;
            }
        }else{
            $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
            $store_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select('order_amount')->sum('order_amount')/100;
            $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select('refund_amount')->sum('refund_amount')/100;
            $fee_amount=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select('receive_fee')->sum('receive_fee')/100;
            $total_num=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select('order_total')->sum('order_total');
            $refund_num=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select('refund_total')->sum('refund_total');
        }
        
        $final_amount = bcsub($store_amount, $fee_amount + $refund_amount, 2);
        $real_amount = bcsub($store_amount, $refund_amount, 2);
        foreach($cashier as $key =>$val){
            $cashier_data = DB::table('merchants')->where('id', $val['merchant_id'])->select('name')->first();
            $store = DB::table('stores')->where('store_id', $val['store_id'])->first();

            $data[$key]['merchant_id'] = $val['merchant_id'];
            $data[$key]['store_name'] = $store->store_name;
            $data[$key]['merchant_name'] = $cashier_data->name??"---";
            
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('merchant_id', $val['merchant_id'])->where('shop_id',$store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('merchant_id', $val['merchant_id'])->where('shop_id',$store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $merchant_amount=0;
                foreach ($ways_amount->get() as $obj) {
                    $merchant_amount += $obj->order_amount;
                }
                $merchant_amount=$merchant_amount/100;
                
                $total_num_zong=DB::connection('old_mysql')->table($table)->where($where)->where('shop_id',$store_id)->select(['order_total']);
                $total_num_zong1=DB::connection('old_mysql')->table($table1)->where($where)->where('shop_id',$store_id)->select(['order_total']);
                $total_num_zong->unionAll($total_num_zong1);
                $total_num=0;
                foreach ($total_num_zong->get() as $obj) {
                    $total_num += $obj->order_total;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $merchant_amount=DB::connection('old_mysql')->table($table)->where($where)->where('merchant_id', $val['merchant_id'])->where('shop_id',$store_id)->select('order_amount')->sum('order_amount')/100;
                $total_num=DB::connection('old_mysql')->table($table)->where($where)->where('merchant_id', $val['merchant_id'])->where('shop_id',$store_id)->select('order_total')->sum('order_total');
            }
            $merchant_amount=$merchant_amount;
            
            $total_num=$total_num;
            
            $data[$key]['merchant_amount'] = $merchant_amount; // 门店总金额
            $data[$key]['total_num'] = $total_num; // 门店总笔数
            if( $store->pid == 0 ){
                $data[$key]['store_name'] = '总店：' . $store->store_name;
            }else{
                $data[$key]['store_name'] = '分店：' . $store->store_name;
            }
            $data[$key]['merchant_num'] = '交易笔数：' . $data[$key]['total_num'] . '笔';
            $data[$key]['money_name'] = '入账金额';
            $data[$key]['store_id'] = $val['store_id'];
        }
        array_multisort( array_column($data, 'merchant_amount'), SORT_DESC, $data );

        $return = array('total_num' => $total_num, 'total_amount' => $store_amount, 'refund_num' => $refund_num, 'refund_amount' => $refund_amount, 'real_amount' => $real_amount, 'fee_amount' => $fee_amount, 'final_amount' => $final_amount, 'merchant_list' => $data);
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($return);
    }
    
    /**
     * 发送HTTP POST请求 <同步>
     * @param url       请求地址
     * @param senid     流水号
     * @param appKey    appKey
     * @param appSecret appSecret
     * @param token     授权码
     * @param taxnum    税号, 普通商户可不填
     * @param method    API名称
     * @param content   私有参数, 标准JSON格式
     * @throws NnuoException
     * @return 成功时返回，其他抛异常
     */
    public function sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token,$taxnum, $method, $content, $timeOut = 6)
    {
        self::checkParam($senid, "senid不能为空");
        self::checkParam($token, "token不能为空");
        self::checkParam($appKey, "appKey不能为空");
        self::checkParam($method, "method不能为空");
        self::checkParam($url, "请求地址URL不能为空");
        self::checkParam($content, "content不能为空");
        self::checkParam($appSecret, "appSecret不能为空");
//        dump(3);die;
        try {
            $timestamp = time();
            $nonce = rand(10000, 1000000000);

            $finalUrl = "{$url}?senid={$senid}&nonce={$nonce}&timestamp={$timestamp}&appkey={$appKey}";

            $urlInfo = parse_url($url);
            if ($urlInfo === FALSE) {
                throw new NnuoException("url解析失败");
            }

            $sign = $this->makeSign($urlInfo["path"], $appSecret, $appKey, $senid, $nonce, $content, $timestamp);

            $headers = array(
                "Content-Type: application/json",
                "X-Nuonuo-Sign: {$sign}",
                "accessToken: {$token}",
                "userTax: {$taxnum}",
                "method: {$method}",
                "sdkVer: " . "2.0.0"
            );
//            print_r($headers);die;
            // 调用开放平台API
            return $this->postCurl($finalUrl, $content, $headers, $timeOut);
        } catch (Exception $e) {
            throw new NnuoException("发送HTTP请求异常:" . $e->getMessage());
        }
    }
    
    public static function checkParam($param, $errMsg){
        if(empty($param)) {
            throw new NnuoException($errMsg);
        }
    }
    
    /**
     * 以post方式发起http调用
     *
     * @param string $url  url
     * @param array $params post参数
     * @param int $second   url执行超时时间，默认30s
     * @throws NnuoException
     */
    private static function postCurl($url, $params, $headers = array(), $second = 30)
    {
        $ch = curl_init();
        $curlVersion = curl_version();

        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        //运行curl
        $data = curl_exec($ch);
//        dump($data);die;
        //返回结果
        if($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_error($ch);
            curl_close($ch);
            throw new NnuoException("curl出错:$error");
        }
    }
    
    /**
     * 计算签名
     *
     * @param path       请求地址
     * @param senid     流水号
     * @param appKey    appKey
     * @param appSecret appSecret
     * @param nonce     随机码
     * @param body    请求包体
     * @param timestamp    时间戳
     * @return 返回签名
     */
    public function MakeSign($path, $appSecret, $appKey, $senid, $nonce, $body, $timestamp)
    {
        $pieces = explode('/', $path);
        $signStr = "a={$pieces[3]}&l={$pieces[2]}&p={$pieces[1]}&k={$appKey}&i={$senid}&n={$nonce}&t={$timestamp}&f={$body}";

        $sign = base64_encode(hash_hmac("sha1", $signStr, $appSecret, true));
        return $sign;
    }
    
    // 诺诺开票接口
    public function billing(Request $request){
        $orderNo = $request->get('out_trade_no', ''); // 订单号
        if(!$orderNo){
            return json_encode([
                'code' => 'E9999',
                'describe' => '订单号不存在'
            ]);
        }
        
        $orders_billing = Db::table('orders_billing')->where([ 'out_trade_no' => $orderNo ])->first(); // 有无此订单号开票记录
        if($orders_billing){
            return json_encode([
                'code' => 'E0000',
                'result' => [
                    'ewmUrl' => $orders_billing->billing_address
                ]
            ]);
        }
        
        
        $order = Db::table('orders')->where([ 'out_trade_no' => $orderNo ])->first(); // 查询订单信息
        if(!$order){
            return json_encode([
                'code' => 'E9999',
                'describe' => '仅支持当日开票'
            ]);
        }
        if($order->pay_status!=1){
            return json_encode([
                'code' => 'E9999',
                'describe' => '仅支持支付成功的订单开票'
            ]);
        }
        $nuonuo_stores = DB::table('nuonuo_stores')->where(['store_id' => $order->store_id])->where(['is_billing' => 1])->first(); // 查找记录
        
        if(!$nuonuo_stores){
            return json_encode([
                'code' => 'E9999',
                'describe' => '商户未配置诺诺开票参数, 请先到代理商后台设置'
            ]);
        }
        /*
        $appKey = '13985881'; // appKey
        $appSecret = '5836FB60AB5A4D5D'; // appSecret
        */
        $appKey=$nuonuo_stores->app_id;
        $appSecret=$nuonuo_stores->app_secret;
        $salerTaxNum = $nuonuo_stores->userTax; // 销售方税号 150301199811285326
        $taxnum = $nuonuo_stores->userTax; // 授权商户的税号
        $token = $nuonuo_stores->access_token;
        if (empty($appKey) || empty($appSecret) || empty($token)) {
            return json_encode([
                'code' => 'E9999',
                'describe' => '商户未配置参数'
            ]);
        }
        // 离线扫码开票接口
//        $method = "nuonuo.ElectronInvoice.saveScanTemp"; // change to your method
        $method = "nuonuo.OpeMplatform.saveScanTemp";
        //nuonuo.OpeMplatform.reInvoice

        $body = array(
            "orderNo" => $orderNo, // aliscan20220804105945037182529
            "salerTaxNum" => $salerTaxNum, // 150301199811285326
            "clerk" => $nuonuo_stores->clerk, // 开票人名称
            "remark" => $nuonuo_stores->remark,
            "invoiceDate" => $order->created_at,
            "detail" => json_encode(array(
                'goodsName' => $nuonuo_stores->goodsName,
                'withTaxFlag' => $nuonuo_stores->withTaxFlag, // 含税标志(0:不含税, 1:含税)
                'goodsCode' => $nuonuo_stores->goodsCode, // 商品编码
                'taxRate' => $nuonuo_stores->taxRate, // 税率（只支持 0.xx x）
                'taxIncludedAmount'=>$order->total_amount, 
            )),
            "orderTotal" => $order->total_amount,
        );
        $json='{';
        
        foreach($body as $k=>$v){
            if($k=='detail'){
               $json=$json.'"'.$k.'"'.':'.'['.$v.'],';
            }else{
                $json=$json.'"'.$k.'"'.':'.'"'.$v.'",';
            }
        }
        $json=rtrim($json,"," );
        
        $body=$json.'}';
        $url = "https://sdk.nuonuo.com/open/v1/services"; // https://sandbox.nuonuocs.cn/open/v1/services

        $senid = uniqid(); // generate your meaningful senid
        
        $res = $this->sendPostSyncRequest($url, $senid, $appKey, $appSecret, $token, $taxnum, $method, $body);
        Log::channel("invoice")->info("sendPostSyncRequest_invoice", [
            "config"=>[
                "appKey"=>$appKey,
                "appSecret"=>$appSecret,
                "token"=>$token,
                "method"=>$method
            ],
            "req" => $body,
            "res" => $res
        ]);
        $result = json_decode($res, true);
        if($result['code'] == 'E0000'){
            Db::table('orders_billing')->insert([ 'out_trade_no' => $orderNo, 'billing_address' => $result['result']['ewmUrl'], 'create_time' => time() ]); // 开票地址存进数据库
        }
        
        return $res;
    }
    
    // 开票二维码
    // public function billing_qrcode(Request $request){
    //     $ewmUrl = $request->get('ewmUrl', '');
    //     print_r($ewmUrl);die;
    // }
    
    // 诺诺开票商户
    function nuonuo_stores(Request $request){
        $nuonuo_id = $request->get('nuonuo_id', '');
        if(empty($nuonuo_id)){
            return json_encode([
                "status" => 2,
                "message" => '没有数据',
            ]);
        }
        
        $nuonuo_stores = DB::table('nuonuo_stores')->where(['id' => $nuonuo_id])->first(); // 查找记录
        $nuonuo_stores->mc = DB::table('tax_code')->where(['bm' => $nuonuo_stores->goodsCode])->value('mc'); // 通过编码 获取开票编码名称

        $nuonuo_category=DB::table('tax_code')->where(['bm' => $nuonuo_stores->goodsCode])->select('id', 'bm', 'mc')->get();
        
        return json_encode([
            "status" => 1,
            "message" => '获取成功',
            "data" => $nuonuo_stores,
            'data_category'=>$nuonuo_category
        ]);
    }
    
    // 诺诺开票商户操作
    function nuonuo_stores_add(Request $request){
        $store_id = $request->get('store_id', ''); // 门店id
        $taxRate = $request->get('taxRate', ''); // 
        $clerk = $request->get('clerk', ''); // 
        $userTax = $request->get('userTax', ''); // 授权商户的税号
        $remark = $request->get('remark', ''); // 
        $goodsName = $request->get('goodsName', ''); // 
        $goodsCode = $request->get('goodsCode', ''); 
        $withTaxFlag = $request->get('withTaxFlag', '');
        $nuonuo_id = $request->get('nuonuo_id', ''); // 诺诺开票配置id
        $access_token=$request->get("access_token","");
        $app_id=$request->get("app_id","");
        $app_secret=$request->get("app_secret","");

        if(empty($store_id) || empty($taxRate) || empty($clerk) || empty($userTax) || empty($remark) || empty($goodsName) || empty($goodsCode)){
            return json_encode([
                "status" => 2,
                "message" => '请填写完整'
            ]);
        }

        if(empty($access_token) || empty($app_id) || empty($app_secret)){
            return json_encode([
                "status" => 2,
                "message" => '请填写完整的配置参数'
            ]);
        }
        
        if($taxRate <= 0){
            return json_encode([
                "status" => 2,
                "message" => '请检查税率格式'
            ]);
        }
    
        $data = [
            'taxRate' => $taxRate,
            'clerk' => $clerk,
            'userTax' => $userTax,
            'remark' => $remark,
            'goodsName' => $goodsName,
            'goodsCode' => $goodsCode,
            'withTaxFlag' => $withTaxFlag,
            "access_token"=>$access_token,
            "app_id"=>$app_id,
            "app_secret"=>$app_secret,
        ];
        
        if($nuonuo_id){
            // 判断不为空
            if(empty($nuonuo_id)){
                return json_encode([
                    "status" => 2,
                    "message" => '缺少参数, 请刷新后重试'
                ]);
            }else{
                $res = DB::table('nuonuo_stores')->where(['id' => $nuonuo_id])->update($data); // 更新记录
            }
        }else{
            $nuonuo_stores_userTax = DB::table('nuonuo_stores')->where(['userTax' => $userTax])->first(); // 查找
            if($nuonuo_stores_userTax){
                return json_encode([
                    "status" => 2,
                    "message" => '税号已存在, 请重试'
                ]);
            }
            
            $is_billing = DB::table('nuonuo_stores')->where(['store_id' => $store_id])->first();
            if(!$is_billing){
                $data['is_billing'] = 1; // 默认开票配置
            }
            
            $data['store_id'] = $store_id;
            $data['create_time'] = time();
            $res = DB::table('nuonuo_stores')->insert($data); // 新增记录
        }
        return json_encode([
            "status" => 1,
            "message" => '操作成功'
        ]);
    }
    
    /**
     * 密钥验证
     * 2022/09/26 15:09
     */
    function add_pass(Request $request){
        try {
            $pass_verify = $this->pass_verify($request); // 密钥验证
            if($pass_verify){
                print_r($pass_verify);die; // 密钥权限不通过
            }else{
                return json_encode([
                    'status' => 1,
                    'message' => '密钥验证通过'
                ]);
            }
        } catch (\Exception $e) {
            return json_encode([
                "status" => 2,
                "message" => $e->getMessage()
            ]);
        }
    }
    
    /**
     * 密钥列表
     * 2022/09/26 11:40
     */
    public function pass_list(Request $request){
        try {
            $pash = $request->path();
            $pass = $request->get('pass', '');
            
            $pass = substr( base64_decode($pass), 0, -5) ;
            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            // print_r($pass_verify);die;
            // $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
            $pass_verify = json_decode($pass_verify, true);
            // print_r( $pass_verify );die;
            if( $pass_verify['status'] != '1'){
                return json_encode(['status' => 2, 'message' => '验证不通过, 请刷新后重试', 'data' => []]);
            }
            // $pass = '000000';
            
            
            // $pass = $request->get('pass', ''); // 密钥
            // print_r($pass);die;

            $pass_permission = DB::table('pass')->where(['pass_md5' => md5($pass)])->first(); // 查询密钥
            // if(!$pass_permission){
            //     $this->status = 2;
            //     $this->message = '密钥错误, 请刷新后重试';
            //     return $this->format($pass);
            // }

            $pass_list = DB::table('pass_permission')->where(['pass_id' => $pass_permission->id])->select()->get(); // 密钥列表

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($pass_list);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }
    
    function pass_verify_do(Request $request){
        $pass = $request->get('pass', '');
        $path = $request->get('path', '');
        
        if( $pass != '' && $path != '' ){
            $res = $this->pass_verify($pass, $path);
            print_r($res);die;
        }else{
            return json_encode([
                "status" => 2,
                "message" => "请输入密钥",
                'data' => $pass
            ]);
        }
    }
    
    /**
     * 创建密钥
     * 2022/09/30 14:43
     */
    public function add_pass_do(Request $request){
        try {
            
            // $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);
            
            // $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            // $pass_verify = json_decode($pass_verify, true);
            // print_r( $this->parseToken() );die;
            // if( $pass_verify['status'] == '1'){
                $pass_id = DB::table('pass')->where(['pass' => $pass])->value('id'); // 密钥id
                $remark = '创建密钥';
                $this->operation_log( $this->parseToken()->user_id, 8, $remark , $pass_id );
            // }else{
            //     return json_encode(['status' => 2, 'message' => '验证不通过', 'data' => []]);
            // }
            
//            $pass_verify = $this->pass_verify($request); // 密钥验证
//            if($pass_verify){
//                print_r($pass_verify);die; // 密钥权限不通过
//            }
//            print_r($pass_verify);die;

            $phone = $request->get('phone', ''); // 手机号
            $permission_id = $request->get('permission_id', ''); // 选中的权限
            if(!$permission_id){
                return json_encode([
                    "status" => 2,
                    "message" => "请选择权限",
                    'data' => $permission_id
                ]);
            }
            $permission_id = explode(',', $permission_id); // 权限数组


            if( strlen($phone) !== 11 ){
                return json_encode([
                    "status" => 2,
                    "message" => "请输入正确的手机号",
                    'data' => $phone
                ]);
            }

            $str_result = '0123456789'; // 随机字符串
            $pass = substr(str_shuffle($str_result), 0, 8); // 生成的8位密钥

            $res = Db::table('pass')->where([ 'pass_md5' => md5($pass) ])->first(); // 查询密钥是否已存在
            if($res){
                return json_encode([
                    "status" => 2,
                    "message" => "创建失败, 请刷新重试",
                    'data' => $pass
                ]);
            }
            
            
            
            
            
            
            

            $role = [
                'pass' => $pass, // 密钥
                'pass_md5' => md5($pass), // md5密钥
                'phone' => $phone, // 备注
                'create_time' => time(),
            ];

            $res = Db::table('pass')->insertGetId($role); // 新增记录并返回记录的id

            foreach($permission_id as $k => $v){
                $permission = DB::table('pass_permission')->where(['id' => $v])->first(); // 循环查询每个权限
                $data = [];
                $data = [
                    'pass_id' => $res, // 密钥id
                    'permission_name' => $permission->permission_name, // 权限名
                    'permission_api' => $permission->permission_api, // api地址
                    'create_time' => time(),
                ];
                Db::table('pass_permission')->insert($data); // 新增生成密钥的权限
            }

            $data = [
                "code" => $pass,
            ];
            $config = SmsConfig::where('type', '16')->first();

            $demo = new AliSms($config->app_key, $config->app_secret);
            $code = rand(100000, 999999);
            $response = $demo->sendSms(
                $config->SignName, // 短信签名
                $config->TemplateCode, // 短信模板编号
                $phone, // 短信接收者
                $data
            );
            // print_r($response);die;

            return json_encode([
                "status" => 1,
                "message" => "添加成功",
                'data' => $pass
            ]);
        } catch (\Exception $e) {
            return json_encode([
                "status" => 2,
                "message" => $e->getMessage()
            ]);
        }
    }
    
    // 签约管理
    function sign_manage(Request $request){
        try {
            $type = $request->get('type', '0'); // 0:未签约 1:已签约
            $phone = $request->get('phone', '');
            
            $where = [];
            if (is_numeric($phone)) {
                $where[] = ['store_id', 'like', '%' . $phone . '%'];
            } else {
                $where[] = ['store_name', 'like', '%' . $phone . '%'];
            }
            
            $obj = DB::table('server_stores')->where($where)->where('status', $type);
            $this->t = $obj->paginate(10)->total();
            $data = $this->page($obj)->get();

            foreach($data as $k => $v){
                $data[$k]->company_name = $this->get_commany_name($data[$k]->company);
                if($v->status == 0){
                    $data[$k]->status_name = '未签约';
                    $data[$k]->created_at = '';
                }else if($v->status == 1){
                    $data[$k]->status_name = '已签约';
                }
                $data[$k]->user_id = DB::table('stores')->where(['store_id' => $v->store_id])->value('user_id');
                $data[$k]->user_name = DB::table('users')->where(['id' => $data[$k]->user_id])->value('name');
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . ' | ' . $exception->getFile() . ' | ' . $exception->getLine()
            ]);
        }
        $this->status = 1;
        $this->message = '数据返回成功';
        return $this->format($data);
    }
    
    // 联动优势进件查询
    function check_linkage_results(Request $request){
        
        $store_id = $request->get('store_id', '');
        if(!$store_id) return;

        $linkages_store_id = Db::table('store_linkages')->where(['store_id' => $store_id])->value('merchant_id');
        if(!$linkages_store_id){
            return json_encode([
                "status" => 2,
                "message" => "请先进件",
            ]);
        }
        
        $linkage_data = [
            'merchant_id' => $store_id,
            'store_id' => $linkages_store_id,
        ];
        $obj = new \App\Api\Controllers\Linkage\BaseController();
        $res = $obj->http_post(false, 'merchant.info.select', $linkage_data);
        $res = json_decode($res, true);
        
        
        if($res['return_value']['verify_status'] == '1'){
            
            return json_encode([
                "status" => 2,
                "message" => "审核中",
                'data' => $res
            ]);
        }else if($res['return_value']['verify_status'] == '2'){
            
            DB::table('store_pay_ways')->where([ 'store_id' => $store_id, 'company' => 'linkage' ])->update([ 'status' => '1', 'status_desc' => '审核通过' ]);
            DB::table('linkage_stores')->where([ 'store_id' => $store_id ])->update([ 'status' => '1' ]);
            
            return json_encode([
                "status" => 1,
                "message" => "审核通过",
                'data' => $res
            ]);
        }else if($res['return_value']['verify_status'] == '3'){
            
            DB::table('store_pay_ways')->where([ 'store_id' => $store_id, 'company' => 'linkage' ])->update([ 'status' => '3', 'status_desc' => '审核驳回' ]);
            DB::table('linkage_stores')->where([ 'store_id' => $store_id ])->update([ 'status' => '2' ]);
            
            return json_encode([
                "status" => 2,
                "message" => $res['return_value']['msg'],
                'data' => $res
            ]);
        }

    }
    
    // 翼支付进件查询
    function check_wingpay_results(Request $request){
        $token = $this->parseToken();
        $store_id = $request->get('store_id', '');
        $wing_stores = DB::table('store_pay_ways')->where(['store_id' => $store_id,'company'=>'wingpay'])->first(); // 查看门店审核状态
        if(empty($wing_stores)){
            return json_encode([
                "status" => 2,
                "message" => "请先开通通道",
            ]);
        }
        $store=DB::table('stores')->where([ 'store_id' => $store_id])->first();
        if($store->store_type=='3'){
            $solutionNo='PS11700';
        }else{
            $solutionNo='PS10418';
        }
        
        $obj = new \App\Api\Controllers\lianfu\PayController();
        $post_array=array('traceLogId'=>'wing'.time(),'loginNo'=>$store->people_phone);
        $url='https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/queryMerchantInputStatus';
        $res = $obj->queryMerchantInputStatus($post_array,$url);
        $res = json_decode($res, true);
        error_log(date('Y-m-d H:i:s')." 【翼支付进件查询】： ".json_encode($res)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");

        if($res['auditStatus'] == 'OPEN_ACCOUNT_SUCCESS'){
            return json_encode([
                "status" => 2,
                "message" => "审核中",
                'data' => $res
            ]);
        }else if($res['auditStatus'] == 'AUDITED_SUCCESS'){
            $obj = new \App\Api\Controllers\lianfu\PayController();
            $sub_ids = $this->getSubIds(469);
            if(in_array($store->user_id,$sub_ids)){
                $wing_user_phone='15954359585';
            }else{
                //$wing_user_phone='19359079377';
                $wing_user_phone='18156861614';
            }
            $post_array=array(
                'traceLogId'=>'wing'.time(),
                'requestSystem'=>'AHHFWHPAY',
                'agentMerchantCode'=>'3178035630163868',
                'employeeId'=>$wing_user_phone,
                'merchantCode'=>$res['merchantCode'],
                'merchantType'=>'PERSON',
                'solutionNo'=>$solutionNo,
                'renewFlag'=>'TRUE',
                'beginDate'=>date('Y-m-d H:i:s',time()),
                'endDate'=>'2025-01-01 00:00:00'
            );
            $url='https://mapi.bestpay.com.cn/mapi/agent/merchantinput/productContract';
            $return = $obj->productContract($post_array,$url);
             error_log(date('Y-m-d H:i:s')." 【翼支付进件查询rs】： ".json_encode($return)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
            if(isset($return['errorCode'])){
                
                return json_encode([
                    "status" => 2,
                    "message" => $return['errorMsg'],
                ]);
            }else{
                $wing=DB::table('wing_stores')->where(['store_id' => $store_id])->first();
                if($wing){
                    DB::table('wing_stores')->where(['store_id' => $store_id])->update(['merchantNo' => $return['merchantCode'],'status'=>'1']);
                }else{
                    DB::table('wing_stores')->where(['store_id' => $store_id])->insert(array('config_id'=>'1234','store_id'=>$store_id,'institutionCode'=>'3178035630163868','merchantNo'=>$return['merchantCode'],'created_at'=>date('Y-m-d H:i:s',time()),'updated_at'=>date('Y-m-d H:i:s',time()),'status'=>'1'));
                }
                $company_config=DB::table('company_config')->where(['store_id' => $store_id,'company' => 'wingpay'])->first();
                
                $data = [];
                $data['store_id'] = $store_id;
                $data['status'] = 1;
                $data['rate'] = $company_config->configure_channel_fee;
                $data['company'] = 'wingpay';
                $data['status_desc'] = '开通成功';
                $this->send_ways_data($data);
                return json_encode([
                    "status" => 1,
                    "message" => "审核通过",
                    'data' => $res
                ]);
            }
        }else if($res['auditStatus'] == 'ENABLE'){
            $wing=DB::table('wing_stores')->where(['store_id' => $store_id])->first();
            if($wing){
                DB::table('wing_stores')->where(['store_id' => $store_id])->update(['merchantNo' => $res['merchantCode']]);
            }else{
                DB::table('wing_stores')->where(['store_id' => $store_id])->insert(array('config_id'=>'1234','store_id'=>$store_id,'institutionCode'=>'3178035630163868','merchantNo'=>$res['merchantCode'],'created_at'=>date('Y-m-d H:i:s',time()),'updated_at'=>date('Y-m-d H:i:s',time()),'status'=>'1'));
            }
            $company_config=DB::table('company_config')->where(['store_id' => $store_id,'company' => 'wingpay'])->first();
            
            $data = [];
            $data['store_id'] = $store_id;
            $data['status'] = 1;
            $data['rate'] = $company_config->configure_channel_fee;
            $data['status_desc'] = '开通成功';
            $data['company'] = 'wingpay';
            $this->send_ways_data($data);
            
            return json_encode([
                "status" => 1,
                "message" => "审核通过",
                'data' => $res
            ]);
        }else if($res['auditStatus'] == 'AUDITED_FAIL' || $res['auditStatus'] == 'OPEN_ACCOUNT_FAIL'){
            $message=isset($res['failureReason'])?$res['failureReason']:'审核失败';
            DB::table('store_pay_ways')->where([ 'store_id' => $store_id , 'company' => 'wingpay' ])->update([ 'status' => '3','status_desc'=>$message ]);
            
            return json_encode([
                "status" => 2,
                "message" =>$message,
                'data' => $res
            ]);
        }

    }
    
    //通道入库
    public function send_ways_data($data)
    {
        try {
            //开启事务
            $all_pay_ways = DB::table('store_ways_desc')->where('company', $data['company'])
                ->get();
            foreach ($all_pay_ways as $k => $v) {
                $gets = StorePayWay::where('store_id', $data['store_id'])
                    ->where('ways_source', $v->ways_source)
                    ->get();
                $count = count($gets);
                $ways = StorePayWay::where('store_id', $data['store_id'])
                    ->where('ways_type', $v->ways_type)
                    ->first();
                try {
                    DB::beginTransaction();
                    $data = [
                        'store_id' => $data['store_id'],
                        'ways_type' => $v->ways_type,
                        'company' => $v->company,
                        'ways_source' => $v->ways_source,
                        'ways_desc' => $v->ways_desc,
                        'sort' => ($count + 1),
                        'rate' => $data['rate'],
                        'settlement_type' => $v->settlement_type,
                        'status' => $data['status'],
                        'status_desc' => $data['status_desc'],
                    ];
                    if ($ways) {
                        $ways->update(
                            [
                                'status' => $data['status'],
                                'status_desc' => $data['status_desc']
                            ]);
                        $ways->save();
                    } else {
                        StorePayWay::create($data);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    Log::info('入库通道55');
                    Log::info($e->getMessage().' | '.$e->getFile().' | '.$e->getLine());
                    DB::rollBack();
                    return [
                        'status' => 2,
                        'message' => '通道入库更新失败1',
                    ];
                }
            }


            return [
                'status' => 1,
                'message' => $data['status_desc'],
            ];

        } catch (\Exception $e) {
            return [
                'status' => '-1',
                'message' => '通道入库更新失败2',
            ];
        }
    }
    
    // 密钥列表
    function key_list(Request $request){
        try {
            $pash = $request->path();
            $pass = $request->get('pass', '');
            $pass = substr(base64_decode($pass), 0, -5);
            
            $pass_verify = $this->pass_verify($pass, $pash); // 密钥验证
            $pass_verify = json_decode($pass_verify, true);

            if( $pass_verify['status'] != '1'){
                return json_encode(['status' => 2, 'message' => '权限不足', 'data' => []]);
            }
            
            $phone = $request->get('phone', '');
            $where = [];
            if ($phone) {
                $where[] = ['phone', 'like', '%'. $phone .'%'];
            }
            
            $obj = DB::table('pass');
            $this->t = $obj->where($where)->count();
            $pass_list = $this->page($obj)->get(); // 密钥列表
            
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($pass_list);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }
    
    /**
     * 修改密钥
     */
    public function pass_find(Request $request){
        try {
            $pass_id = $request->get('id', '');
            
            $pass = DB::table('pass')->where(['id' => $pass_id])->first(); // 查询密钥
            if(!$pass){
                $this->status = 2;
                $this->message = '密钥异常,请联系皖付通中台';
                return $this->format($pass);
            }
            $pass_permission = DB::table('pass_permission')->where(['pass_id' => $pass->id])->select()->get(); // 密钥权限列表
            
            
            $key_list = DB::table('pass_permission')->where(['pass_id' => '81'])->select()->get(); // 密钥列表
            $pass_list = [];
            foreach($key_list as $k => $v){
                $pass_auth=DB::table('pass_permission')->where(['pass_id' => $pass_id, 'permission_api' => $v->permission_api])->value('id');
                $pass_list[$k]['status'] = $pass_auth?1:0;
                $pass_list[$k]['id'] = $v->id;
                $pass_list[$k]['pass_id'] = $v->pass_id;
                $pass_list[$k]['permission_name'] = $v->permission_name;
            }
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($pass_list);
        } catch (\Exception $exception) {
            $this->status = -1;
            $this->message = $exception->getMessage();
            return $this->format();
        }
    }
    
    // 修改密钥
    function pass_edit(Request $request){
        try {
            $pass = $request->get('pass', ''); // 当前密钥
            $pass = substr(base64_decode($pass), 0, -5);
            
            // $pass_verify = DB::table('pass')->where(['pass' => $pass])->first(); // 查询当前密钥
            // if($pass_verify->id != '81'){
            //     $this->status = 2;
            //     $this->message = '权限不足';
            //     return $this->format($pass);
            // }
            
            $pass_id = $request->get('pass_id', ''); // 修改的密钥id
            $permission_id = $request->get('permission_id', '');
            $permission_id = explode(',', $permission_id); // 修改的权限数组
            $key = Db::table('pass')->where([ 'id' => $pass_id ])->first();
            if(!$key){
                $this->status = 2;
                $this->message = '密钥异常,请联系皖付通中台';
                return $this->format($key);
            }
            
            
            
            // 只加权限 不删权限
            foreach($permission_id as $k => $v){ // 循环查询修改的每个权限
                $permission_api = DB::table('pass_permission')->where(['id' => $v])->first();
                $permission_api_old = DB::table('pass_permission')->where(['pass_id' => $pass_id, 'permission_api' => $permission_api->permission_api])->first();
                if(!$permission_api_old){ // 修改的权限 原先没有这个权限 要添加这个权限
                    $data = [];
                    $data = [
                        'pass_id' => $pass_id, // 密钥id
                        'permission_name' => $permission_api->permission_name, // 权限名
                        'permission_api' => $permission_api->permission_api, // api地址
                        'create_time' => time(),
                    ];
                    Db::table('pass_permission')->insert($data); // 新增生成密钥的权限
                }
            }
            
            
            
            /*
            先全删 再全加
            */
            // $key_list = DB::table('pass_permission')->where(['pass_id' => $key->id])->select()->get(); // 密钥列表
            // foreach($key_list as $k => $v){
            //     Db::table('pass_permission')->delete(['id' => $v->id]); // 
            // }
            // foreach($permission_id as $k => $v){
            //     $permission = DB::table('pass_permission')->where(['id' => $v])->first(); // 循环查询每个权限
            //     $data = [];
            //     $data = [
            //         'pass_id' => $pass_id, // 密钥id
            //         'permission_name' => $permission->permission_name, // 权限名
            //         'permission_api' => $permission->permission_api, // api地址
            //         'create_time' => time(),
            //     ];
            //     Db::table('pass_permission')->insert($data); // 新增生成密钥的权限
            // }
            
            
            
            return json_encode([
                "status" => 1,
                "message" => "修改成功",
                'data' => ''
            ]);
        } catch (\Exception $e) {
            return json_encode([
                "status" => 2,
                "message" => $e->getMessage()
            ]);
        }
    }

    function get_waycount(Request $request){
        $format = [];
        $user_id = $this->parseToken()->user_id; // 获取登录的代理商信息
        $curHdIndex=$request->get('curHdIndex', '');
        $start_data=$request->get('start_data', '');
        $end_data=$request->get('end_data', '');
        $store_id=$request->get('store_id', '');
        try {
            $curHdTit = '';
            switch (intval($curHdIndex)) {
                case 1://今日
                    $date_start = date('Y-m-d 00:00:00');
                    $date_end = date('Y-m-d 23:59:59');
                    $curHdTit = '今日';
                    break;
                case 2://昨日
                    $date_start = date('Y-m-d 00:00:00', strtotime("-1 day"));
                    $date_end = date('Y-m-d 23:59:59', strtotime("-1 day"));
                    $curHdTit = '昨日';
                    break;
                case 3://上周
                    $date_start = date('Y-m-d 00:00:00', strtotime('last week'));
                    $date_end = date('Y-m-d 23:59:59', strtotime('this week -1 day'));
                    $curHdTit = '上周';
                    break;
                case 4://本月
                    $date_start = date('Y-m-01 00:00:00');
                    $date_end = date('Y-m-t 23:59:59');
                    $curHdTit = '本月';
                    break;
                case 5://上月
                    $date_start = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
                    $date_end = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
                    $curHdTit = '上月';
                    break;
            }
            $time_end = strtotime($date_end);
            $time_start = strtotime($date_start);
            if ($time_end<$date_start){
                throw new \Exception("结束时间不能大于开始时间");
            }
            if ($time_start<strtotime('2023-06-01')){
                throw new \Exception("查询最小时间不能低于2023-06-01");
            }
            if ($time_end>strtotime(date('Y-m-t 23:59:59'))){
                throw new \Exception("查询最大时间不能高于当天");
            }
            $db = DB::connection();

            $user_rates = $db->table('user_rates')->where('user_id', $user_id)->distinct('company')->pluck(DB::raw("CONCAT(server_rate,':',era_rate,':',rate,':',yu_rate)"), 'ways_type')->toArray();
            $ways_source = $db->table('store_pay_ways')->where('store_id', $store_id)->pluck('ways_source', 'ways_type')->toArray();
            $monthTotal = $this->getMonthDifference(strtotime($date_start), strtotime($date_end));

            $tableName = 'wft_stores_orders_' . date('Ym', strtotime($date_start)) . '_bill';
            $pluck = DB::connection('old_mysql')->table($tableName)
                ->where('store_id', $store_id)
                ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                ->select([
                    'receive_code',
                    'receive_rate',
                    'receive_model',
                    DB::raw('sum(receive_fee) as receive_fee'),
                    DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                    DB::raw('sum(order_total) as order_total'),
                    DB::raw('sum(order_amount) as order_amount'),
                    DB::raw('sum(refund_total) as refund_total'),
                    DB::raw('sum(refund_amount) as refund_amount'),
                ])
                ->groupBy(Db::raw('receive_code,receive_rate,receive_model'));
            for ($i = 0; $i < $monthTotal; $i++) {
                $num = $i + 1;
                $numTime = strtotime("+" . $num . " month", strtotime($date_start));
                $tableName = 'wft_stores_orders_' . date('Ym', $numTime) . '_bill';
                $union_pluck = DB::connection('old_mysql')->table($tableName)
                    ->where('store_id', $store_id)
                    ->whereBetween('bill_date', [strtotime($date_start), strtotime($date_end)])
                    ->select([
                        'receive_code',
                        'receive_rate',
                        'receive_model',
                        DB::raw('sum(receive_fee) as receive_fee'),
                        DB::raw('sum(receive_refund_fee) as receive_refund_fee'),
                        DB::raw('sum(order_total) as order_total'),
                        DB::raw('sum(order_amount) as order_amount'),
                        DB::raw('sum(refund_total) as refund_total'),
                        DB::raw('sum(refund_amount) as refund_amount'),
                    ])
                    ->groupBy(Db::raw('receive_code,receive_rate,receive_model'));
                $pluck->unionAll($union_pluck);
            }

            $total_amount = '0.00';
            $refund_amount = '0.00';
            $total_commission = '0.00';
            $total_fee = '0.00';

            $weixin_total_amount = '0.00';
            $weixin_refund_amount = '0.00';
            $weixin_total = '0';

            $alipay_total_amount = '0.00';
            $alipay_refund_amount = '0.00';
            $alipay_total = '0';

            $unionpay_total_amount = '0.00';
            $unionpay_refund_amount = '0.00';
            $unionpay_total = '0';

            $bestpay_total_amount = '0.00';
            $bestpay_refund_amount = '0.00';
            $bestpay_total = '0';

            foreach ($pluck->get() as $obj) {
                $item = (array)$obj;

                $company_rates = explode(':', $user_rates[$item['receive_code']]);
                $user_rate = $company_rates[$item['receive_model'] - 1];

//                if ($user_rate > 0 && $item['receive_rate'] > $user_rate) {
                    $difference = bcmul(bcdiv(bcsub($item['receive_rate'], $user_rate, 2), 100, 4), bcsub($item['order_amount'], $item['refund_amount']), 2);
                    $difference = bcdiv($difference, 100, 2);
                    $total_commission = bcadd($total_commission, $difference, 2);
//                }
                $total_amount = bcadd($total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                $refund_amount = bcadd($refund_amount, bcdiv($item['refund_amount'], 100, 2), 2);
                $total_fee = bcadd($total_fee, bcdiv($item['receive_fee'], 100, 2), 2);
                switch ($ways_source[$item['receive_code']]) {
                    case 'alipay':
                        $alipay_total_amount = bcadd($alipay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $alipay_refund_amount = bcadd($alipay_refund_amount, bcdiv($item['refund_amount'], 100, 2), 2);
                        $alipay_total = bcadd($alipay_total, $item['order_total']);
                        break;
                    case 'weixin':
                        $weixin_total_amount = bcadd($weixin_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $weixin_refund_amount = bcadd($weixin_refund_amount, bcdiv($item['refund_amount'], 100, 2), 2);
                        $weixin_total = bcadd($weixin_total, $item['order_total']);
                        break;
                    case 'Bestpay':
                        $bestpay_total_amount = bcadd($bestpay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $bestpay_refund_amount = bcadd($bestpay_refund_amount, bcdiv($item['refund_amount'], 100, 2), 2);
                        $bestpay_total = bcadd($bestpay_total, $item['order_total']);
                        break;
                    case 'unionpay':
                        $unionpay_total_amount = bcadd($unionpay_total_amount, bcdiv($item['order_amount'], 100, 2), 2);
                        $unionpay_refund_amount = bcadd($unionpay_refund_amount, bcdiv($item['refund_amount'], 100, 2), 2);
                        $unionpay_total = bcadd($unionpay_total, $item['order_total']);
                        break;
                }

            }


            $format=[
                "total_amount"=> bcsub($total_amount,$refund_amount,2),
                "total_commission"=> $total_commission,
                "total_fee"=> $total_fee,
                "store_name"=> DB::table('stores')->where('store_id',$store_id)->value('store_name'),

                'start_date' => $date_start,
                'end_date' => $date_end,
                'time' => implode(' - ', [$date_start, $date_end]),

                "weixin_amount"=> $weixin_total_amount,
                "weixin_num"=> $weixin_total,
                "wx_refund_amount"=> $weixin_refund_amount,

                "alipay_amount"=> $alipay_total_amount,
                "alipay_num"=> $alipay_total,
                "zfb_refund_amount"=> $alipay_refund_amount,

                "unionpay_amount"=> $unionpay_total_amount,
                "unionpay_num"=> $unionpay_total,
                "un_refund_amount"=> $unionpay_refund_amount,

                "bestpay_amount"=> $bestpay_total_amount,
                "bestpay_num"=> $bestpay_total,
                "tel_refund_amount"=> $bestpay_refund_amount,

                "shuaka_amount"=> 0,
                "shuaka_num"=> 0,
                "shuaka_refund_amount"=> 0

            ];
            $this->status = 1;
            $this->message = 'Ok';
        } catch (\Exception $e) {
            $this->status = 2;
            $this->message = $e->getMessage();
        }
        return $this->format($format);
    }
    
    // 代理商小程序-数据统计-支付方式
    function _get_waycount(Request $request){
        $token = $this->parseToken();
        $token_user_id = $token->user_id;
        $curHdIndex=$request->get('curHdIndex', '');
        $start_data=$request->get('start_data', '');
        $end_data=$request->get('end_data', '');
        $store_id=$request->get('store_id', '');
        
        $store=DB::table('stores')->where('store_id', $store_id)->select('store_id','store_name','id')->first();
        $p_stores=DB::table('stores')->where('pid',$store->id)->select('store_id')->get();
        if(!empty($p_stores[0]->store_id)){
            $p_store_data[0]=$store->store_id;
            $p_stores=json_decode($p_stores,true);
            foreach($p_stores as $k1=>$v1){
                $p_store_data[]=$v1['store_id'];
            }
        }else{
            $p_store_data[0]=$store->store_id;
        }
        if($curHdIndex == 1){
            $where[] = ['created_at', '>=', date('Y-m-d', time()).' 00:00:00'];
            $where[] = ['created_at', '<=', date('Y-m-d', time()).' 23:59:59'];
            $start_date=date('Y-m-d', time());
            $end_date=date('Y-m-d', time());
            
            $stores_day_count = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->select();
            //总收款
            $total_amount=$stores_day_count->sum('total_amount');
            //总佣金
            $total_commission='待结算';
            $total_fee=$stores_day_count->sum('refund_amount');
            
            $weixin_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'weixin')->select()->sum('total_amount');
            $weixin_num = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'weixin')->select()->count('total_amount');
            $wx_refund_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->where('ways_source', 'weixin')->select()->sum('total_amount');
            
            $alipay_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'alipay')->select()->sum('total_amount');
            $alipay_num = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'alipay')->select()->count('total_amount');
            $zfb_refund_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->where('ways_source', 'alipay')->select()->sum('total_amount');
            
            $unionpay_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'unionpay')->select()->sum('total_amount');
            $unionpay_num = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'unionpay')->select()->count('total_amount');
            $un_refund_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->where('ways_source', 'unionpay')->select()->sum('total_amount');
            
            $bestpay_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'bestpay')->select()->sum('total_amount');
            $bestpay_num = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'bestpay')->select()->count('total_amount');
            $tel_refund_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->where('ways_source', 'bestpay')->select()->sum('total_amount');
            
            $shuaka_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'unionpay')->where('ways_type_desc', '刷卡支付')->select()->sum('total_amount');
            $shuaka_num = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [1])->where('ways_source', 'unionpay')->where('ways_type_desc', '刷卡支付')->select()->count('total_amount');
            $shuaka_refund_amount = Order::whereIn('store_id', $p_store_data)->where($where)->whereIn('pay_status', [6])->where('ways_source', 'unionpay')->where('ways_type_desc', '刷卡支付')->select()->sum('total_amount');
            
            $return_data=array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'store_name'=>$store->store_name,
                'time'=>date('Y-m-d', time()).' 00:00:00'.'-'.date('Y-m-d', time()).' 23:59:59',
                
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==2){
            $where[] = ['bill_date', '>=', strtotime('yesterday')];
            $where[] = ['bill_date', '<=', strtotime('yesterday')+86399];
            $where_c[] = ['settling_day', '>=', date('Y-m-d',strtotime("-1 day"))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d',strtotime("-1 day"));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $ways_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $ways_amount_zong += $obj->order_amount;
                }
                
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount->unionAll($ways_amount1);
                $refund_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $refund_amount_zong += $obj->refund_amount;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('refund_amount')->sum('refund_amount')/100;
                
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }
            
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay',5=>'shuaka');
            foreach($ways_source as $k=>$v){
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')->distinct()->get();
                $ways=json_decode($ways,true);
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount += $obj->order_amount;
                    }
                    
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total->unionAll($order_total1);
                    $total=0;
                    foreach ($order_total->get() as $obj) {
                        $total += $obj->order_total;
                    }
                    
                    $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount->unionAll($refund_amount1);
                    $refund=0;
                    foreach ($refund_amount->get() as $obj) {
                        $refund += $obj->refund_amount;
                    }
                    
                    if($v=='weixin'){
                        $weixin_count=$ways_amount/100;
                        $weixin_refund=$refund/100;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount/100;
                        $alipay_refund=$refund/100;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount/100;
                        $unionpay_refund=$refund/100;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount/100;
                        $Bestpay_refund=$refund/100;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount/100;
                        $shuaka_refund=$refund/100;
                        $shuaka_total=$total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $refund=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    $total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                    // $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    if($v=='weixin'){
                        $weixin_count=$ways_amount;
                        $weixin_refund=$refund;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount;
                        $alipay_refund=$refund;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount;
                        $unionpay_refund=$refund;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount;
                        $Bestpay_refund=$refund;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount;
                        $shuaka_refund=$refund;
                        $shuaka_total=$total;
                    }
                    
                }
            }
            
            $total_amount = $ways_amount_zong;
            $total_commission = $total_commission;
            $total_fee = $refund_amount_zong;
            
            $weixin_amount = $weixin_count;
            $weixin_num = $weixin_total;
            $wx_refund_amount = $weixin_refund;
            
            $alipay_amount = $alipay_count;
            $alipay_num = $alipay_total;
            $zfb_refund_amount = $alipay_refund;
            
            $unionpay_amount = $unionpay_count;
            $unionpay_num = $unionpay_total;
            $un_refund_amount = $unionpay_refund;
            
            $shuaka_amount = $shuaka_count;
            $shuaka_num = $shuaka_total;
            $shuaka_refund_amount = $shuaka_refund;
            
            $bestpay_amount =$Bestpay_count;
            $bestpay_num = $Bestpay_total;
            $tel_refund_amount = $Bestpay_refund;

            $return_data = array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_name'=>$store->store_name,
                'time'=>date('Y-m-d',strtotime("-1 day")).'-'.date('Y-m-d',strtotime("-1 day")),
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==3){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime('last week'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d', strtotime('this week -1 day'))];
            $start_date=date('Y-m-d', strtotime('last week'));
            $end_date=date('Y-m-d', strtotime('this week -1 day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $ways_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $ways_amount_zong += $obj->order_amount;
                }
                
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount->unionAll($ways_amount1);
                $refund_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $refund_amount_zong += $obj->refund_amount;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('refund_amount')->sum('refund_amount')/100;
                
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }
            
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay',5=>'shuaka');
            foreach($ways_source as $k=>$v){
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')->distinct()->get();
                $ways=json_decode($ways,true);
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount += $obj->order_amount;
                    }
                    
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total->unionAll($order_total1);
                    $total=0;
                    foreach ($order_total->get() as $obj) {
                        $total += $obj->order_total;
                    }
                    
                    $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount->unionAll($refund_amount1);
                    $refund=0;
                    foreach ($refund_amount->get() as $obj) {
                        $refund += $obj->refund_amount;
                    }
                    
                    if($v=='weixin'){
                        $weixin_count=$ways_amount/100;
                        $weixin_refund=$refund/100;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount/100;
                        $alipay_refund=$refund/100;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount/100;
                        $unionpay_refund=$refund/100;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount/100;
                        $Bestpay_refund=$refund/100;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount/100;
                        $shuaka_refund=$refund/100;
                        $shuaka_total=$total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $refund=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    $total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                    // $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    if($v=='weixin'){
                        $weixin_count=$ways_amount;
                        $weixin_refund=$refund;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount;
                        $alipay_refund=$refund;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount;
                        $unionpay_refund=$refund;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount;
                        $Bestpay_refund=$refund;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount;
                        $shuaka_refund=$refund;
                        $shuaka_total=$total;
                    }
                    
                }
            }
            
            $total_amount = $ways_amount_zong;
            $total_commission = $total_commission;
            $total_fee = $refund_amount_zong;
            
            $weixin_amount = $weixin_count;
            $weixin_num = $weixin_total;
            $wx_refund_amount = $weixin_refund;
            
            $alipay_amount = $alipay_count;
            $alipay_num = $alipay_total;
            $zfb_refund_amount = $alipay_refund;
            
            $unionpay_amount = $unionpay_count;
            $unionpay_num = $unionpay_total;
            $un_refund_amount = $unionpay_refund;
            
            $shuaka_amount = $shuaka_count;
            $shuaka_num = $shuaka_total;
            $shuaka_refund_amount = $shuaka_refund;
            
            $bestpay_amount =$Bestpay_count;
            $bestpay_num = $Bestpay_total;
            $tel_refund_amount = $Bestpay_refund;

            $return_data = array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_name'=>$store->store_name,
                'time'=>date('Y-m-d', strtotime('last week')).'-'.date('Y-m-d', strtotime('this week -1 day')),
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==4){
            $where[] = ['bill_date', '>=', mktime(0,0,0,date('m'),1,date('Y'))];
            $where[] = ['bill_date', '<=', mktime(0,0,0,date('m'),date('d'),date('Y'))-1];
            $where_c[] = ['settling_day', '>=', date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-d',strtotime("-1 day"))];
            $start_date=date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00'));
            $end_date=date('Y-m-d',strtotime("-1 day"));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $ways_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $ways_amount_zong += $obj->order_amount;
                }
                
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount->unionAll($ways_amount1);
                $refund_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $refund_amount_zong += $obj->refund_amount;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('refund_amount')->sum('refund_amount')/100;
                
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }
            
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay',5=>'shuaka');
            foreach($ways_source as $k=>$v){
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')->distinct()->get();
                $ways=json_decode($ways,true);
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount += $obj->order_amount;
                    }
                    
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total->unionAll($order_total1);
                    $total=0;
                    foreach ($order_total->get() as $obj) {
                        $total += $obj->order_total;
                    }
                    
                    $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount->unionAll($refund_amount1);
                    $refund=0;
                    foreach ($refund_amount->get() as $obj) {
                        $refund += $obj->refund_amount;
                    }
                    
                    if($v=='weixin'){
                        $weixin_count=$ways_amount/100;
                        $weixin_refund=$refund/100;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount/100;
                        $alipay_refund=$refund/100;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount/100;
                        $unionpay_refund=$refund/100;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount/100;
                        $Bestpay_refund=$refund/100;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount/100;
                        $shuaka_refund=$refund/100;
                        $shuaka_total=$total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $refund=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    $total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                    // $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    if($v=='weixin'){
                        $weixin_count=$ways_amount;
                        $weixin_refund=$refund;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount;
                        $alipay_refund=$refund;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount;
                        $unionpay_refund=$refund;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount;
                        $Bestpay_refund=$refund;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount;
                        $shuaka_refund=$refund;
                        $shuaka_total=$total;
                    }
                    
                }
            }
            
            $total_amount = $ways_amount_zong;
            $total_commission = $total_commission;
            $total_fee = $refund_amount_zong;
            
            $weixin_amount = $weixin_count;
            $weixin_num = $weixin_total;
            $wx_refund_amount = $weixin_refund;
            
            $alipay_amount = $alipay_count;
            $alipay_num = $alipay_total;
            $zfb_refund_amount = $alipay_refund;
            
            $unionpay_amount = $unionpay_count;
            $unionpay_num = $unionpay_total;
            $un_refund_amount = $unionpay_refund;
            
            $shuaka_amount = $shuaka_count;
            $shuaka_num = $shuaka_total;
            $shuaka_refund_amount = $shuaka_refund;
            
            $bestpay_amount =$Bestpay_count;
            $bestpay_num = $Bestpay_total;
            $tel_refund_amount = $Bestpay_refund;

            $return_data = array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_name'=>$store->store_name,
                'time'=>date('Y-m-d', strtotime(date('Y-m', time()) . '-01 00:00:00')).' 00:00:00'.'-'.date('Y-m-d',strtotime("-1 day")),
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }else if($curHdIndex==5){
            $where[] = ['bill_date', '>=', strtotime(date('Y-m-01 00:00:00',strtotime(date('Y-m-01') . " - 1 month")))];
            $where[] = ['bill_date', '<=', strtotime(date("Y-m-d 23:59:59", strtotime(-date('d').'day')))];
            $where_c[] = ['settling_day', '>=', date('Y-m-01', strtotime('-1 month'))];
            $where_c[] = ['settling_day', '<=', date('Y-m-t', strtotime('-1 month'))];
            $start_date=date('Y-m-01',strtotime(date('Y-m-01') . " - 1 month"));
            $end_date=date("Y-m-d", strtotime(-date('d').'day'));
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $ways_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $ways_amount_zong += $obj->order_amount;
                }
                
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount->unionAll($ways_amount1);
                $refund_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $refund_amount_zong += $obj->refund_amount;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('refund_amount')->sum('refund_amount')/100;
                
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }
            
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay',5=>'shuaka');
            foreach($ways_source as $k=>$v){
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')->distinct()->get();
                $ways=json_decode($ways,true);
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $ways_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $ways_amount += $obj->order_amount;
                    }
                    
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total->unionAll($order_total1);
                    $total=0;
                    foreach ($order_total->get() as $obj) {
                        $total += $obj->order_total;
                    }
                    
                    $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount->unionAll($refund_amount1);
                    $refund=0;
                    foreach ($refund_amount->get() as $obj) {
                        $refund += $obj->refund_amount;
                    }
                    
                    if($v=='weixin'){
                        $weixin_count=$ways_amount/100;
                        $weixin_refund=$refund/100;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount/100;
                        $alipay_refund=$refund/100;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount/100;
                        $unionpay_refund=$refund/100;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount/100;
                        $Bestpay_refund=$refund/100;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount/100;
                        $shuaka_refund=$refund/100;
                        $shuaka_total=$total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $refund=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    $total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                    // $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    if($v=='weixin'){
                        $weixin_count=$ways_amount;
                        $weixin_refund=$refund;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount;
                        $alipay_refund=$refund;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount;
                        $unionpay_refund=$refund;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount;
                        $Bestpay_refund=$refund;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount;
                        $shuaka_refund=$refund;
                        $shuaka_total=$total;
                    }
                    
                }
            }
            
            $total_amount = $ways_amount_zong;
            $total_commission = $total_commission;
            $total_fee = $refund_amount_zong;
            
            $weixin_amount = $weixin_count;
            $weixin_num = $weixin_total;
            $wx_refund_amount = $weixin_refund;
            
            $alipay_amount = $alipay_count;
            $alipay_num = $alipay_total;
            $zfb_refund_amount = $alipay_refund;
            
            $unionpay_amount = $unionpay_count;
            $unionpay_num = $unionpay_total;
            $un_refund_amount = $unionpay_refund;
            
            $shuaka_amount = $shuaka_count;
            $shuaka_num = $shuaka_total;
            $shuaka_refund_amount = $shuaka_refund;
            
            $bestpay_amount =$Bestpay_count;
            $bestpay_num = $Bestpay_total;
            $tel_refund_amount = $Bestpay_refund;
            
            $return_data = array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_name'=>$store->store_name,
                'time'=>date('Y-m-01', strtotime('-1 month')).'-'.date('Y-m-t', strtotime('-1 month')),
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
            
        }else if( $curHdIndex == 6 ){
            $start_data = $request->get('start_data', '');
            $end_data = $request->get('end_data', '');
            $start_date=$start_data;
            $end_date=$end_data;
            if ($start_data != $end_data) {
                $date = ((strtotime($end_data) > strtotime($start_data)))?true:false;
                if (!$date) {
                    $this->status = '2';
                    $this->message = '开始时间不能超过结束时间';
                    return $this->format(2);
                }
            }
            // //限制时间
            $date = (strtotime($end_data) - strtotime($start_data)) / 86400;
            $day = 31;
            if ($date > $day) {
                $this->status = '2';
                $this->message = "时间筛选不能超过 $day 天";
                return $this->format(2);
            }
            
            $where[] = ['bill_date', '>=', strtotime($start_data.' 00:00:00')];
            $where[] = ['bill_date', '<=', strtotime($end_data.' 23:59:59')];
            $where_c[] = ['settling_day', '>=', $start_data];
            $where_c[] = ['settling_day', '<=', $end_data];
            
            if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['order_amount']);
                $ways_amount->unionAll($ways_amount1);
                $ways_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $ways_amount_zong += $obj->order_amount;
                }
                
                $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->select(['refund_amount']);
                $ways_amount->unionAll($ways_amount1);
                $refund_amount_zong=0;
                foreach ($ways_amount->get() as $obj) {
                    $refund_amount_zong += $obj->refund_amount;
                }
            }else{
                $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                $ways_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('order_amount')->sum('order_amount')/100;
                $refund_amount_zong=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->select('refund_amount')->sum('refund_amount')/100;
                
            }
            $start_commission=$start_date;
            $end_commission=$end_date;
            $get_commission=$start_commission.','.$end_commission;
            if(count($p_store_data)>100){
                $total_commission=DB::table('company_day_commission')->where('store_id', $store_id)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }else{
                $total_commission=DB::table('company_day_commission')->whereIn('store_id', $p_store_data)->where($where_c)->where('user_id',$token_user_id)->select('commission_money')->sum('commission_money');
            }
            
            $ways_source=array(0=>'weixin',1=>'alipay',3=>'unionpay',4=>'Bestpay',5=>'shuaka');
            foreach($ways_source as $k=>$v){
                $ways=DB::table('store_ways_desc')->where('ways_source',$v)->select('ways_type as receive_code')->distinct()->get();
                $ways=json_decode($ways,true);
                if (date('Ym', strtotime($end_date)) - date('Ym', strtotime($start_date)) > 0) {
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $table1='wft_stores_orders_' . date('Ym', strtotime($end_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_amount']);
                    $ways_amount->unionAll($ways_amount1);
                    $store_amount=0;
                    foreach ($ways_amount->get() as $obj) {
                        $store_amount += $obj->order_amount;
                    }
                    
                    $order_total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['order_total']);
                    $order_total->unionAll($order_total1);
                    $total=0;
                    foreach ($order_total->get() as $obj) {
                        $total += $obj->order_total;
                    }
                    
                    $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount1=DB::connection('old_mysql')->table($table1)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select(['refund_amount']);
                    $refund_amount->unionAll($refund_amount1);
                    $refund=0;
                    foreach ($refund_amount->get() as $obj) {
                        $refund += $obj->refund_amount;
                    }
                    
                    if($v=='weixin'){
                        $weixin_count=$store_amount/100;
                        $weixin_refund=$refund/100;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$store_amount/100;
                        $alipay_refund=$refund/100;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$store_amount/100;
                        $unionpay_refund=$refund/100;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$store_amount/100;
                        $Bestpay_refund=$refund/100;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$store_amount/100;
                        $shuaka_refund=$refund/100;
                        $shuaka_total=$total;
                    }
                }else{
                    $table='wft_stores_orders_' . date('Ym', strtotime($start_date)) . '_bill';
                    $ways_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_amount')->sum('order_amount')/100;
                    $refund=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    $total=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('order_total')->sum('order_total');
                    // $refund_amount=DB::connection('old_mysql')->table($table)->where($where)->where('store_id', $store_id)->whereIn('receive_code',$ways)->select('refund_amount')->sum('refund_amount')/100;
                    if($v=='weixin'){
                        $weixin_count=$ways_amount;
                        $weixin_refund=$refund;
                        $weixin_total=$total;
                    }else if($v=='alipay'){
                        $alipay_count=$ways_amount;
                        $alipay_refund=$refund;
                        $alipay_total=$total;
                    }else if($v=='unionpay'){
                        $unionpay_count=$ways_amount;
                        $unionpay_refund=$refund;
                        $unionpay_total=$total;
                    }else if($v=='Bestpay'){
                        $Bestpay_count=$ways_amount;
                        $Bestpay_refund=$refund;
                        $Bestpay_total=$total;
                    }else if($v=='shuaka'){
                        $shuaka_count=$ways_amount;
                        $shuaka_refund=$refund;
                        $shuaka_total=$total;
                    }
                    
                }
            }
            
            $total_amount = $ways_amount_zong/100;
            $total_commission = $total_commission;
            $total_fee = $refund_amount_zong/100;
            
            $weixin_amount = $weixin_count;
            $weixin_num = $weixin_total;
            $wx_refund_amount = $weixin_refund;
            
            $alipay_amount = $alipay_count;
            $alipay_num = $alipay_total;
            $zfb_refund_amount = $alipay_refund;
            
            $unionpay_amount = $unionpay_count;
            $unionpay_num = $unionpay_total;
            $un_refund_amount = $unionpay_refund;
            
            $shuaka_amount = $shuaka_count;
            $shuaka_num = $shuaka_total;
            $shuaka_refund_amount = $shuaka_refund;
            
            $bestpay_amount =$Bestpay_count;
            $bestpay_num = $Bestpay_total;
            $tel_refund_amount = $Bestpay_refund;

            $return_data = array(
                'total_amount'=>$total_amount,
                'total_commission'=>$total_commission,
                'total_fee'=>$total_fee,
                'store_name'=>$store->store_name,
                'time'=>$start_data . '-' . $end_data,
                'start_date'=>$start_date,
                'end_date'=>$end_date,
                
                'weixin_amount' => $weixin_amount,
                'weixin_num' => $weixin_num,
                'wx_refund_amount' => $wx_refund_amount,
                'alipay_amount' => $alipay_amount,
                'alipay_num' => $alipay_num,
                'zfb_refund_amount' => $zfb_refund_amount,
                'unionpay_amount' => $unionpay_amount,
                'unionpay_num' => $unionpay_num,
                'un_refund_amount' => $un_refund_amount,
                'bestpay_amount' => $bestpay_amount,
                'bestpay_num' => $bestpay_num,
                'tel_refund_amount' => $tel_refund_amount,
                'shuaka_amount' => $shuaka_amount,
                'shuaka_num' => $shuaka_num,
                'shuaka_refund_amount' => $shuaka_refund_amount,
            );
            $this->status = '1';
            $this->message = '数据返回成功';
            return $this->format($return_data);
        }
    }
    
    // 诺诺税收分类编码
    public function nuonuo_category(Request $request){
        
        $category_name = $request->get('tax_code', '');

        $where = [];
        if ($category_name) {
            $where[] = ['mc', 'like', '%'. $category_name .'%'];
        }
        $data = DB::table('tax_code')->where($where)->select('id', 'bm', 'mc')->get();

        $this->status = 1;
        $this->message = '返回数据成功';
        return $this->format($data);
    }
    
    // public function m_ceshi(){
    //     // fastcgi_finish_request();
    //     $settling_day='2023-07-15';
    //     $stores=DB::table('stores')->where('pid','0')->select('store_id','id')->get();
    //     // $stores=DB::table('stores')->select('store_id','id')->get();
    //     // Cache::forever('ceshi', $stores);
    //     // Cache::delete('ceshi');
    //     // $stores = Cache::get('ceshi');
    //     foreach ($stores as $k=>$v){
    //         $p_stores = DB::table('stores')->where('pid', $v->id)->select('store_id')->get(); // 查找总店下的分店
    //         if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
    //             $store_ids[0] = $v->store_id;
    //             $p_stores = json_decode($p_stores, true);
    //             foreach($p_stores as $k1 => $v1){
    //                 $store_ids[] = $v1['store_id'];
    //             }
    //         }else{
    //             $store_ids[0] = $v->store_id;
    //         }
    //         $day_count=DB::table('stores_day_count')->whereIn('store_id',$store_ids)->where('settling_day',$settling_day)->select('store_amount')->sum('store_amount');
    //         $day_company=DB::table('company_day_commission')->where('user_id',1)->whereIn('store_id',$store_ids)->where('settling_day',$settling_day)->select('total_amount')->sum('total_amount');
    //         if($day_count!=$day_company){
    //             file_put_contents('store_id.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //         }
    //         unset($store_ids);
    //     }
    //     file_put_contents('store_id.log',var_export(111,true)."\r\n",FILE_APPEND);
    // }
    
    // public function m_ceshi(){
    //     $obj = new \App\Api\Controllers\lianfu\PayController();
    //     $post_array=array('traceLogId'=>'wing'.time(),'loginNo'=>'13701469728');
    //     $url='https://mapi.bestpay.com.cn/mapi/agent/merchantInputService/queryMerchantInputStatus';
    //     $return = $obj->queryMerchantInputStatus($post_array,$url);
    //     echo '<pre>';
    //     print_r($return);
    //     die;
    //     $return = json_decode($return, true);
    // }
    
    //  public function m_ceshi(){
    //     $obj = new \App\Api\Controllers\lianfu\PayController();
    //     $post_array=array('traceLogId'=>'wing'.time(),'requestSystem'=>'AHHFWHPAY','agentMerchantCode'=>'3178035630163868','employeeId'=>'18605581186','merchantCode'=>'610003102580639','merchantType'=>'PERSON','solutionNo'=>'PS10418','renewFlag'=>'TRUE','beginDate'=>date('Y-m-d H:i:s',time()),'endDate'=>date('Y-m-d H:i:s',time()+86400));
    //     $url='https://mapi.bestpay.com.cn/mapi/agent/merchantinput/productContract';
    //     $return = $obj->productContract($post_array,$url);
    //     $return = json_decode($return, true);
    // }
    
    // public function m_ceshi(){
    //     $obj = new \App\Api\Controllers\lianfu\PayController();
    //     $post_array=array('traceLogId'=>'wing'.time(),'requestSystem'=>'AHHFWHPAY','agentMerchantCode'=>'3178035630163868','merchantCode'=>'610003102580639','solutionNo'=>'PS10418');
    //     $url='https://mapi.bestpay.com.cn/mapi/agent/merchantinput/queryProductSignResult';
    //     $return = $obj->queryProductSignResult($post_array,$url);
    //     $return = json_decode($return, true);
    // }
    
    // public function m_ceshi(){
    //     $where[] = ['created_at', '>=', '2023-05-01 00:00:00'];
    //     $where[] = ['created_at', '<=', '2023-05-01 23:59:59'];
    //     $company_config=DB::table('company_config')->get();
    //     //4：预充 3：通道扣费 2：代扣 1：服务费
    //     foreach($company_config as $k=>$v){
    //         unset($store);
    //         unset($p_stores);
    //         unset($store_ids);
    //         $store = DB::table('stores')->where('store_id', $v->store_id)->select('store_id', 'store_name', 'id')->first(); // 查找总店
            
    //         $p_stores = DB::table('stores')->where('pid', $store->id)->select('store_id')->get(); // 查找总店下的分店
    //         if( !empty( $p_stores[0]->store_id ) ){ // 合并总店和分店
    //             $store_ids[0] = $store->store_id;
    //             $p_stores = json_decode($p_stores, true);
    //             foreach($p_stores as $k1 => $v1){
    //                 $pay_ways=DB::table('store_pay_ways')->where('store_id', $v1['store_id'])->where('company', $v->company)->where('status', 1)->select('company')->distinct()->first();
    //                 if(empty($pay_ways)){
    //                     $store_ids[] = $v1['store_id'];
    //                 }
    //             }
    //         }else{
    //             $store_ids[0] = $store->store_id;
    //         }
    //         $total_amount=DB::table('orders_20230501')->whereIn('store_id',$store_ids)->where('company',$v->company)->where($where)->whereIn('pay_status', [1, 6])->select('total_amount')->sum('total_amount');
    //         if($total_amount>0){
    //             $company_day_commission=DB::table('company_day_commission')->where('user_id','1')->where('settling_day','2023-05-01')->where('store_id',$v->store_id)->where('company',$v->company)->first();
    //                 if(isset($company_day_commission->total_amount)){
    //                     if($total_amount!=$company_day_commission->total_amount){
    //                     file_put_contents('ceshif1.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //                 }
    //             }else{
    //                 file_put_contents('ceshif1.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //             }
                
    //         }

    //     }
    // }
    
    public function m_ceshi(){
        $service_day_money=DB::table('service_day_money')->where('id','>=','199624')->get();
        foreach ($service_day_money as $k=>$v){
            if($v->user_id=='0'){
                $store=DB::table('stores')->where('store_id',$v->store_id)->first();
                $store_money=$store->store_money+$v->count;
                DB::table('stores')->where('store_id',$store->store_id)->update(array('store_money'=>$store_money));
                DB::table('service_day_money')->where('id',$v->id)->delete();
            }else{
                $user=DB::table('users')->where('id',$v->user_id)->first();
                $end_money=$user->settlement_money+$v->count;
                DB::table('users')->where('id',$v->user_id)->update(array('settlement_money'=>$end_money));
                DB::table('service_day_money')->where('id',$v->id)->delete();
            }
        }
        
        // $service_day_money=DB::table('service_day_money')->whereIn('store_id',['2022116112324848603','2022120145111303435','2022011710345214362','2022011615454295616','2022617195919035050'])->where('user_id','347')->get();
        // echo '<pre>';
        // print_r($service_day_money);
        // die;
        // foreach ($service_day_money as $k=>$v){
        //     $user=DB::table('users')->where('id','347')->first();
        //     $end_money=$user->settlement_money+$v->count;
        //     DB::table('users')->where('id','347')->update(array('settlement_money'=>$end_money));
        //     DB::table('service_day_money')->where('id',$v->id)->delete();
        // }
    }
    
    // public function m_ceshi(){
    //     $date_time=date("Y-m-d",strtotime("-1 day"));
    //     $table='orders_' . date("Ymd", strtotime("-1 day"));
    //     // $stores=DB::table('stores')->select('store_id')->get();
    //     // foreach ($stores as $k=>$v){
    //     //     DB::table('store_day')->insert(array('settling_day'=>$date_time,'store_id'=>$v->store_id));
    //     // }
    //     $stores=DB::table('store_day')->select('store_id','settling_day')->limit(500)->get()->toArray();
    //     foreach ($stores as $k=>$v){
    //         //查询总店是否有分店
    //         $store=DB::table('stores')->where(array('store_id'=>$v->store_id))->select('pid','id')->first();
    //         if($store->pid>0){
    //             //获取总店门店id
    //             $sub_store=DB::table('stores')->where(array('id'=>$store->pid))->select('store_id')->first();
    //         }
    //         $id=$store->id;
    //         $where[] = ['orders.created_at', '>=', $date_time.' 00:00:00'];
    //         $where[] = ['orders.created_at', '<=', $date_time.' 23:59:59'];
    //         //门店汇总
    //         $stores_data = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [1, 6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total'),DB::raw('sum(orders.refund_amount) as refund_amount'),DB::raw('sum(orders.fee_amount) as fee_amount')])->first();
                
    //         //退款汇总
    //         $stores_data_refund = DB::table('orders')->join('stores', function ($join) {$join->on('orders.store_id', '=', 'stores.store_id');})->whereIn('orders.pay_status', [6])->where($where)->where(function ($query) use($id) {$query->where('stores.id', $id)->orwhere('stores.pid',$id);return $query;})->select([DB::raw('count(orders.out_trade_no) as total')])->first();
    //         //微信汇总
    //         $stores_data_wx= DB::table('orders')->join('stores', function ($join) {
    //             $join->on('orders.store_id', '=', 'stores.store_id');
    //         })
    //             ->whereIn('orders.pay_status', [1,6])
    //             ->where('orders.ways_source', 'weixin')
    //             ->where($where)
    //             ->where(function ($query) use($id) {
    //                 $query->where('stores.id', $id)->orwhere('stores.pid',$id);
    //                 return $query;
    //             })
    //             ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
    //             ->first();
                
    //         //支付宝汇总
    //         $stores_data_zfb= DB::table('orders')->join('stores', function ($join) {
    //             $join->on('orders.store_id', '=', 'stores.store_id');
    //         })
    //             ->whereIn('orders.pay_status', [1,6])
    //             ->where('orders.ways_source', 'alipay')
    //             ->where($where)
    //             ->where(function ($query) use($id) {
    //                 $query->where('stores.id', $id)->orwhere('stores.pid',$id);
    //                 return $query;
    //             })
    //             ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
    //             ->first();
                
    //         //云闪付汇总
    //         $stores_data_uni= DB::table('orders')->join('stores', function ($join) {
    //             $join->on('orders.store_id', '=', 'stores.store_id');
    //         })
    //             ->whereIn('orders.pay_status', [1,6])
    //             ->where('orders.ways_source', 'unionpay')
    //             ->where($where)
    //             ->where(function ($query) use($id) {
    //                 $query->where('stores.id', $id)->orwhere('stores.pid',$id);
    //                 return $query;
    //             })
    //             ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
    //             ->first();
                
    //         //翼支付汇总
    //         $stores_data_wing= DB::table('orders')->join('stores', function ($join) {
    //             $join->on('orders.store_id', '=', 'stores.store_id');
    //         })
    //             ->whereIn('orders.pay_status', [1,6])
    //             ->where('orders.ways_source', 'wingpay')
    //             ->where($where)
    //             ->where(function ($query) use($id) {
    //                 $query->where('stores.id', $id)->orwhere('stores.pid',$id);
    //                 return $query;
    //             })
    //             ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
    //             ->first();
    //         $arr=array(
    //             'store_amount'=>$stores_data->total_amount-$stores_data->refund_amount,
    //             'refund_amount'=>$stores_data->refund_amount,
    //             'fee_amount'=>$stores_data->fee_amount,
    //             'store_order_count'=>$stores_data->total,
    //             'refund_order_num'=>$stores_data_refund->total,
    //             'store_id'=> $v->store_id,
    //             'sub_storeid'=>$store->pid==0 ? 0 :$upstore->store_id,
    //             'settling_day'=>$v->settling_day,
    //             'weixin_amount'=>$stores_data_wx->total_amount,
    //             'weixin_num'=>$stores_data_wx->total,
    //             'alipay_amount'=>$stores_data_zfb->total_amount,
    //             'alipay_num'=>$stores_data_zfb->total,
    //             'unionpay_amount'=>$stores_data_uni->total_amount,
    //             'unionpay_num'=>$stores_data_uni->total,
    //             'bestpay_amount'=>$stores_data_wing->total_amount?$stores_data_wing->total_amount:0,
    //             'bestpay_num'=>$stores_data_wing->total,
    //             'created_at'=>time()
    //         );
    //         DB::table('stores_day_count')->insert($arr);
    //         $merchant_stores = DB::table('merchant_stores')->where('store_id',$v->store_id)->select('merchant_id')->get();
    //         foreach($merchant_stores as $key=>$val){
    //         //收银员汇总
    //         $stores_data_merch= DB::table('orders')->join('stores', function ($join) {
    //             $join->on('orders.store_id', '=', 'stores.store_id');
    //         })
    //             ->where('orders.merchant_id', $val->merchant_id)
    //             ->whereIn('orders.pay_status', [1,6])
    //             ->where($where)
    //             ->where(function ($query) use($id) {
    //                 $query->where('stores.id', $id)->orwhere('stores.pid',$id);
    //                 return $query;
    //             })
    //             ->select([DB::raw('sum(orders.total_amount) as total_amount'),DB::raw('count(orders.out_trade_no) as total')])
    //             ->first();
    //             $mer=array(
    //                 'store_id'=>$v->store_id,
    //                 'merchant_id'=>$val->merchant_id,
    //                 'merchant_money'=>$stores_data_merch->total_amount?$stores_data_merch->total_amount:0,
    //                 'merchant_num'=>$stores_data_merch->total,
    //                 'created_at'=>time(),
    //                 'settling_day'=>$v->settling_day,
    //             );
    //             DB::table('stores_cash_count')->insert($mer);
    //         }
    //     }
    // }
    // public function m_ceshi(){
    //     // fastcgi_finish_request();
    //     // $stores=DB::table('stores')->get();
    //     // foreach ($stores as $k=>$v){
    //     //     $way=DB::table('store_pay_ways')->where('store_id',$v->store_id)->where('status',1)->select('company')->distinct()->get();
    //     //     foreach($way as $key=>$val){
    //     //         $company_config=DB::table('company_config')->where('store_id',$v->store_id)->where('company',$val->company)->first();
    //     //         if(empty($company_config)){
    //     //             file_put_contents('b45432535341.log',var_export($v->id,true)."\r\n",FILE_APPEND);
    //     //         }
    //     //     }
    //     // }
    //     // session_start();
    //     // $company_config=DB::table('company_config')->get();
    //     // foreach ($company_config as $k=>$v){
    //     //     $user_id = DB::table('stores')->where([ 'store_id' => $v->store_id ])->value('user_id');
    //     //     unset($_SESSION['users']);
    //     //     $users = $this->recursion1($user_id);
    //     //     $users = json_decode($users, true);
    //     //     foreach ($users as $k1=>$v1){
    //     //         $user_rates=DB::table('user_rates')->where('user_id', $v1['id'])->where('company',$v->company)->first();
    //     //         if($v->model=='4'){
    //     //             if($v->configure_channel_fee<$user_rates->yu_rate){
    //     //                 file_put_contents('986364654.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //     //             }
    //     //         }else if($v->model=='3'){
    //     //             if($v->configure_channel_fee<$user_rates->rate){
    //     //                 file_put_contents('986364654.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //     //             }
    //     //         }else if($v->model=='2'){
    //     //             if($v->configure_channel_fee<$user_rates->era_rate){
    //     //                 file_put_contents('986364654.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //     //             }
    //     //         }else if($v->model=='2'){
    //     //             if($v->configure_channel_fee<$user_rates->server_rate){
    //     //                 file_put_contents('986364654.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //     //             }
    //     //         }
    //     //     }
    //     // }
        
    //     $stores=DB::table('stores')->where('pid',0)->where('is_close',0)->where('is_delete',0)->select('store_id')->get();
    //     foreach ($stores as $k=>$v){
    //         echo '<pre>';
    //         print_r($v);
    //         die;
    //     }
        
        
    //     // $store_id='202210293337103148';
    //     // $store=DB::table('stores')->where('store_id',$store_id)->first();
    //     // echo '<pre>';
    //     // print_r($store);
    //     // die;
    // }
    
    // public function m_ceshi(){
    //     // echo '<pre>';
    //     // print_r(111);
    //     // die;
    //     // fastcgi_finish_request();
        
        
        
    //     // $company_config=DB::table('company_config')->where('store_id','2023816112053187852')->where('company','wingpay')->get();
    //     // $company_config=DB::table('company_config')->get();
    //     // // unset($company_config[0]);
    //     // foreach ($company_config as $k=>$v){
    //     //     // DB::table('company_config')->where('id',$v->id)->delete();
    //     //     // DB::table('company_day_commission')->where('store_id',$v->store_id)->where('company','wingpay')->delete();
    //     //     $count=DB::table('company_config')->where('store_id',$v->store_id)->where('company',$v->company)->where('model',$v->model)->get();
    //     //     $num=count($count);
    //     //     if($num>1){
    //     //         file_put_contents('b235212.log',var_export($v->store_id,true)."\r\n",FILE_APPEND);
    //     //     }
            
    //     // }
    //     // file_put_contents('b235212.log',var_export(2222,true)."\r\n",FILE_APPEND);
        
    //     $where[] = ['created_at', '>=', '2023-09-01 00:00:00'];
    //     $where[] = ['created_at', '<=', '2023-09-30 23:59:59'];
    //     $refund_orders=DB::table('refund_orders')->where($where)->get();
    //     foreach ($refund_orders as $k=>$v){
    //         $order=DB::table('orders')->where('out_trade_no',$v->out_trade_no)->first();
    //         if($order->pay_status!='6'){
    //             file_put_contents('bsdds.log',var_export($v->out_trade_no,true)."\r\n",FILE_APPEND);
    //         }
    //     }
        
    // }
    
    // public function m_ceshi(){
    //     $date=date('Ymd',time()-86400);
    //     $temp=base_path().'/public/bestpay/'.'bestpay'.$date.'_3178035630163868.csv';
    //     $file = fopen($temp, 'r');
    //     $keys = fgetcsv($file); // 获取列名作为键值
    //     $data = array();
    //     while (($row = fgetcsv($file)) !== false) {
    //         $data[] = eval('return '.iconv('gbk','utf-8',var_export($row,true)).';');
    //     }
    //     fclose($file);
    //     unset($data[0]);
    //     unset($data[1]);
    //     unset($data[2]);
    //     unset($data[3]);
    //     unset($data[4]);
    //     unset($data[5]);
    //     unset($data[6]);
    //     foreach ($data as $k=>$v){
    //         if(isset($v[1])){
    //             $order=DB::table('orders')->where('out_trade_no',trim($v[1]))->first();
    //             if(empty($order)){
    //                 if(strlen($v[13])<10){
    //                     if(strstr($v[5],'WECHATPAY')){
    //                       $ways_type='30050';
    //                       $ways_type_desc='微信支付';
    //                       $ways_source='weixin';
    //                       $ways_source_desc='微信支付';
    //                     }else if(strstr($v[5],'ALIPAY')){
    //                       $ways_type='30051';
    //                       $ways_type_desc='支付宝';
    //                       $ways_source='alipay';
    //                       $ways_source_desc='支付宝';
    //                     }else if(strstr($v[5],'QUICKPASS')){
    //                       $ways_type='30052';
    //                       $ways_type_desc='云闪付';
    //                       $ways_source='unionpay';
    //                       $ways_source_desc='云闪付';
    //                     }else{
    //                       $ways_type='30053';
    //                       $ways_type_desc='翼支付';
    //                       $ways_source='Bestpay';
    //                       $ways_source_desc='翼支付';
    //                     }
    //                     $store_id= DB::table('wing_stores')->where('merchantNo', trim($v[16]))->select('store_id')->first();
    //                     $store=DB::table('stores')->where('store_id', $store_id->store_id)->first();
    //                     $order=array('config_id'=>'1234','out_trade_no'=>trim($v[1]),'trade_no'=>trim($v[1]),'store_id'=>$store->store_id,'merchant_name'=>'店长','user_id'=>$store->user_id,'merchant_id'=>$store->merchant_id
    //                     ,'store_name'=>$store->store_name,'ways_type'=>$ways_type,'rate'=>'0.35','ways_type_desc'=>$ways_type_desc,'ways_source'=>$ways_source,'ways_source_desc'=>$ways_source_desc,'pay_method'=>'app'
    //                     ,'company'=>'wingpay','total_amount'=>$v[7],'receipt_amount'=>$v[7],'buyer_pay_amount'=>$v[7],'pay_amount'=>$v[7],'fee_amount'=>$v[7]
    //                     ,'shop_price'=>$v[7],'shop_count'=>1,'status'=>1,'pay_status'=>1,'pay_status_desc'=>'支付成功','pay_time'=>$v[4],'created_at'=>$v[4],'updated_at'=>$v[4]);
    //                     DB::table('orders')->insert($order);
    //                     file_put_contents('b646456454.log',var_export(trim($v[1]),true)."\r\n",FILE_APPEND);
    //                 }
    //             }
    //         }
    //     }
    // }
    
    // public function m_ceshi(){
    //     $id='444';
    //     $user_ids = $this->getSubIds($id);
    //     $stores = DB::table('stores')->whereIn('user_id', $user_ids)->select('store_id', 'store_name', 'id','user_id','people_phone')->get(); // 查找总店
    //     foreach ($stores as $k=>$v){
    //         $wing_stores=DB::table('wing_stores')->where('store_id', $v->store_id)->first();
    //         $user=DB::table('users')->where('id', $v->user_id)->first();
    //         if(!empty($wing_stores)){
    //             $arr[]=array(
    //                 'store_id'=>$v->store_id. "\t",
    //                 'store_name'=>$v->store_name,
    //                 'wing_merch'=>$wing_stores->merchantNo. "\t",
    //                 'people_phone'=>$v->people_phone. "\t",
    //                 'user_name'=>$user->name,
    //             );
    //         }
    //     }
    //     $filename = '翼支付商户.csv';
    //     $s_array = ['筛选条件：' . '暂不导出'];
    //     $tileArray = ['门店ID','门店名称','翼支付商户号', '手机号码','所属代理'];

    //     ini_set('memory_limit', '512M');
    //     ini_set('max_execution_time', 0);
    //     ob_end_clean();
    //     ob_start();
    //     header("Content-Type: text/csv");
    //     header("Content-Disposition:filename=" . $filename);
    //     $fp = fopen('php://output', 'w');
    //     fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));

    //     fputcsv($fp, $s_array);
    //     fputcsv($fp, []);
    //     fputcsv($fp, $tileArray);
    //     $index = 0;
    //     foreach ($arr as $item) {
    //         $index++;
    //         fputcsv($fp, $item);
    //     }

    //     ob_flush();
    //     flush();
    //     ob_end_clean();
    // }
    
    public function check_yinsheng_results (Request $request)
    {
        $store_id = $request->get('store_id', '');
        $data = DB::table('ysepay_stores')->where(['store_id' => $store_id])->first(); // 查看门店审核状态
        if(empty($data) || empty($data->sign_url)){
            return json_encode([
                "status" => 2,
                "message" => "请先开通通道",
            ]);
        }
        return json_encode([
            "status" => 1,
            "message" => "审核通过",
            'data' => ['url' => $data->sign_url]
        ]);
    }
    
}